So you can upload an image to Firebase database, but it has to be in binary or something weird and it's generally not accepted practice. To make these urls unique in storage you can upload them under CityName -> autoIdKey which will be unique. This also means all the images of a city will be under it's name in storage which might be handy later.
You can get the current users city using this code
import Foundation
import MapKit
typealias JSONDictionary = [String:Any]
class LocationServices {
let shared = LocationServices()
let locManager = CLLocationManager()
var currentLocation: CLLocation!
let authStatus = CLLocationManager.authorizationStatus()
let inUse = CLAuthorizationStatus.authorizedWhenInUse
let always = CLAuthorizationStatus.authorizedAlways
func getAdress(completion: @escaping (_ address: JSONDictionary?, _ error: Error?) -> ()) {
self.locManager.requestWhenInUseAuthorization()
if self.authStatus == inUse || self.authStatus == always {
self.currentLocation = locManager.location
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(self.currentLocation) { placemarks, error in
if let e = error {
completion(nil, e)
} else {
let placeArray = placemarks as? [CLPlacemark]
var placeMark: CLPlacemark!
placeMark = placeArray?[0]
guard let address = placeMark.addressDictionary as? JSONDictionary else {
return
}
completion(address, nil)
}
}
}
}
}
Function to get the city name:
func getCityName() -> String {
LocationServices.shared.getAdress { address, error in
if let a = address, let city = a["City"] as? String {
return city
}
else {
return "NO_CITY_NAME"
}
}
}
Upload and get the storage URL:
@IBAction func postPressed(_ sender: Any) {
// get the cityname
let city = getCityName()
let uid = Auth.auth().currentUser!.uid
let ref = Database.database().reference()
let storage = Storage.storage().reference(forURL: "gs://YourUrlHere")
let key = ref.child("pois").childByAutoId().key // unique key
let imageRef = storage.child("pois").child(city).child("\(key).jpg")
let data = UIImageJPEGRepresentation(photo, 0.6)
let uploadTask = imageRef.putData(data!, metadata: nil) { (metadata, error) in
if error != nil {
// do something
return
}
imageRef.downloadURL(completion: {(url, error) in
// upload of image worked now get the url to upload to your database
if let url = url, let author = Auth.auth().currentUser?.displayName {
let feed = ["city": ,
"pathToImage": url.absoluteString, // here is your storage url to upload to Firebase DB
: key] as [String: Any]
let postFeed = ["\(key)" : feed]
ref.child("pois").updateChildValues(postFeed, withCompletionBlock: { (error, success) in
if error != nil {
// do something
return
}
else {
// data successfully uploaded
}
})
}
})
}
uploadTask.resume()
uploadTask.observe(.success) { (snapshot) in
// do something when upload is finished
return
}
uploadTask.observe(.failure) { (snapshot) in
// do something on failure
return
}
}