In a model's class Location, I get the name of the current city:
var currentLatitude: Double!
var currentLongitude: Double!
var currentLocation: String!
var currentCity: String!
func getLocationName() {
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
self.nowUpdateUI()
})
}
In view controller I want to update the UI and update my label to show the current city.
However, self.currentCity = city happens inside of a closure. So if I just run a func in view controller:
func updateUI() {
cityLbl.text = Location.sharedInstance.currentCity
}
I'm not getting anywhere because the closure haven't finished running.
I've been advised to add a completion handler to getLocationName() and inside of it, perform the call to a func that will update the UI.
However, from all the tutorials out there on closures, completion handlers, it is not clear to me how to achieve that.
How to construct a completion handler, pass it as an arg to getLocationName() and how to call getLocationName from view controller?
To handle this situation you have multiple option.
Create delegate/protocol with your Location class
Create one protocol and implement that protocol method with your ViewController and declare its instance in your Location class. After then in the completionHandler of reverseGeocodeLocation call this delegate method. Check Apple documentation on Protocol for more details.
You can create completionHandler with your getLocationName method of Location class.
Add completionHandler with getLocationName and called that completionHandler inside the completionHandler of reverseGeocodeLocation like this way.
func getLocationName(completionHandler: #escaping (_ success: Bool) -> Void) {
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
completionHandler(false)
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
completionHandler(true)
//self.nowUpdateUI()
})
}
Now in ViewController where you are calling this function call your updateUI method inside the completion block.
Location.sharedInstance.getLocationName { (success) in
if success {//If successfully got response
self.updateUI()
}
}
You can add observer for (NS)NotificationCenter.
Register the observer with (NS)NotificationCenter and then post the notification inside the completionHandler of reverseGeocodeLocation. You can get more detail on this with this StackOverflow Post.
// I thing issue back ground thread you need to update your UI in main thread
var currentLatitude: Double!
var currentLongitude: Double!
var currentLocation: String!
var currentCity: String!
func getLocationName() {
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
DispatchQueue.main.async {
self.nowUpdateUI()
// Update your UI in main thread
}
})
}
This entire piece of your code:
completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
self.nowUpdateUI()
}
)
is already happening in the completionHandler (which happens after everything is finished) Just also run your updateUI() inside the completionHandler. So your end code would be :
completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
DispatchQueue.main.async {
updateUI()
}
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
self.nowUpdateUI()
}
)
The reason you have to use DispatchQueue.main is because your completionHandler is on a backgroundqueue but you MUST always do you UI related stuff from your mainQueue—so users get the fastest changing in their UI without any glitches. Imagine if you were doing on a background thread and it was happening slow
Related
I have a form that gets a new user's name and zip code. When the user presses Save, I use Core Location to take the zip code and find the associated city and state. At that point I want a completion handler to save the form data along with the city and state.
But for some reason, the completion part isn't kicking in. I'm still trying to figure out completion handlers but I thought I got pretty close... (obviously I need to deal with error handling and the code could be more concise.)
Button(action: {
self.getCityStateFromPostalCode(zip: self.zip, completion: {
//This isn't getting called
let newCustomer = Customer(context: self.moc)
newCustomer.custName = self.name
newCustomer.custZip = self.zip
newCustomer.custState = self.state
newCustomer.custCity = self.city
self.appDelegate.saveContext()
})
}) {
Text("Save")
}
func getCityStateFromPostalCode(zip: String, completion: #escaping () -> ()) {
let geocoder = CLGeocoder()
var city = ""
var state = ""
geocoder.geocodeAddressString(zip) { (placemarks, error) in
if let placemark = placemarks?[0] {
if placemark.postalCode == zip {
city = placemark.locality!
state = placemark.administrativeArea!
self.city = city
self.state = state
}
}
}
}
In your function you're not calling the completion parameter:
func getCityStateFromPostalCode(zip: String, completion: #escaping () -> ()) {
let geocoder = CLGeocoder()
var city = ""
var state = ""
geocoder.geocodeAddressString(zip) { (placemarks, error) in
if let placemark = placemarks?[0] {
if placemark.postalCode == zip {
city = placemark.locality!
state = placemark.administrativeArea!
self.city = city
self.state = state
}
}
completion() // <- add this (may be moved depending on the `error` parameter
}
}
My ultimate goal is to display annotations on a Map from MapKit. However, loading data from firebase does not work.
Here is the code:
var hotels = [Hotel]()
override func viewDidLoad() {
super.viewDidLoad()
map.delegate = self
checkLocationServices()
observe()
}
The function observe is the following:
func observe() {
Data().getAllHotel { (hotelA) -> (Void) in
if let hotel = hotelA {
print("hotel: ", hotel)
self.hotels.append(hotel)
let hotelAnnotation = MKPointAnnotation()
hotelAnnotation.title = "\(hotel.hotelName)"
hotelAnnotation.coordinate = CLLocationCoordinate2D(latitude: hotel.latitude, longitude: hotel.longitude)
self.map.addAnnotation(hotelAnnotation)
}
}
}
Note that the print in the if statement is not empty.
However the line hotelAnnotation.title causes a bug unexpected nil and I don't understand why.
Additionnally here is the getAllHotel function inside the Data class:
func getAllHotel(closure: HotelClosure?) {
let ref = Ref().databaseHotels
ref.observe(.childAdded) { (snapshot) in
if let dict = snapshot.value as? Dictionary<String, AnyObject> {
let hotel = self.fromDictToHotel(key: snapshot.key, dict: dict)
closure?(hotel)
} else {
closure?(nil)
}
}
}
func fromDictToHotel(key: String, dict: Dictionary<String, AnyObject>) -> Hotel? {
guard let hotelName = dict["name"] as? String else { return nil }
guard let latitude = dict["latitude"] as? Double else { return nil }
guard let longitude = dict["longitude"] as? Double else { return nil }
let hotelDescription = dict["description"] as? String
let hotelGrade = dict["grade"] as? Double
let hotelImageUrl = dict["hotelImageUrl"] as? String
let hotel = Hotel(hid: key, hotelName: hotelName, hotelDescription: hotelDescription, latitude: latitude, longitude: longitude, grade: hotelGrade, url: hotelImageUrl)
return hotel
}
Thanks in advance for your help!
I'm trying to to calculate the distance from an event to my current location, sort the results and populate that in a tableview. I keep getting error for optional unwrapped value distance is nil.
private func observeEvents() {
refHandle = ref.observe(.childAdded, with: { (snapshot) -> Void in
let eventDetails = snapshot.value as! Dictionary<String, AnyObject>
let eventID = snapshot.key
let location = eventDetails["location"] as! String!
//calculating distance
self.forwardGeocoding(address: location!)
let distance = self.eventLocation?.distance(from: self.currentLocation!) as Double!
//end calculating
let dateTime = eventDetails["dateTime"] as! String!
let addedByUser = eventDetails["addedByUser"] as! String!
let attending = eventDetails["attendance"] as! String!
if let name = eventDetails["eventName"] as! String! , name.characters.count > 0
{
self.events.append(Events(id:eventID, name: name, location: location!, dateTime: dateTime!, addedByUser: addedByUser!, attending: attending! , distance: distance!))
self.events.sort(by: { $0.distance < $1.distance})
self.tableView.reloadData()
} else {
print("Error ! Can't load events from database")
}
})
} //load events data to uitableview
I created a function to return a CLLocation from an address
func forwardGeocoding(address: String) {
CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in
if error != nil {
print(error!)
return
}
if (placemarks?.count)! > 0 {
let placemark = placemarks?[0]
self.eventLocation = placemark?.location
}
})
}
I finally figured out the answer. The issue was the function for distance is called asynchronously there for the result would always be nil. I created a completion handler for the forwardGeocoding function to return latitude and longitude from the address string and call the result inside the nested firebase listener. Here is the code, I hope if someone ran into something similar problem to me will find it helpful.
//Get lat and long
func getCoordinates(address: String, completionHandler: #escaping (_ lat: CLLocationDegrees?, _ long: CLLocationDegrees?, _ error: Error?) -> ()) -> Void {
var _:CLLocationDegrees
var _:CLLocationDegrees
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks: [CLPlacemark]!, error: Error!) in
if error != nil {
print("Geocode failed with error: \(error.localizedDescription)")
} else if placemarks.count > 0 {
let placemark = placemarks[0] as CLPlacemark
let location = placemark.location
let lat = location?.coordinate.latitude
let long = location?.coordinate.longitude
completionHandler(lat, long, nil)
}
}
}
Nested call in firebase listener
refHandle = ref.observe(.childAdded, with: { (snapshot) -> Void in
let location = event["address"] as! String
self.getCoordinates(address: location!) { lat, long, error in
if error != nil {
print("Error")
} else {
self.latitude = lat
self.longitude = long
let distance = CLLocation(latitude: self.latitude!,longitude: self.longitude!).distance(from: self.currentLocation!)
if let name = eventDetails["eventName"] as! String! , name.characters.count > 0
{
self.events.append(Events(id:eventID, name: name, location: location!, dateTime: dateTime!, addedByUser: addedByUser!, attending: attending!, distance: distance))
self.events.sort(by: { $0.distance < $1.distance})
self.tableView.reloadData()
} else {
print("Error ! Can't load events from database")
}
}
}
})
Trying to get name of a city, while having latitude and longitude.
Inside a model class Location, I'm using reverseGeocodeLocation(location: , completionHandler: ) func that comes with CLGeocoder (part of CoreLocation).
func getLocationName() {
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
})
}
However, in ViewController, after running the getLocationName(), the location.currentCity is nil, since the completion handler is async, and wasn't finished yet.
How can I make sure that the completion handler is finished running so I can access location.currentCity ?
Pass a closure as a function parameter in your getLocationName which
you can call inside the reverseGeocodeLocation closure.
func updateLocation(currentCity : String) -> Void
{
print(currentCity)
}
func getLocationName(callback : #escaping (String) -> Void)
{
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String
{
self.currentCity = city
callback(city)
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
})
}
In your ViewController...
getLocationName(callback: updateLocation)
I would create a function where location.currentCity is used, and call this function from the completion handler
So if your code looks like:
func foo() {
var location
getLocationName()
print(location.currentcity) // nil
}
change it to:
func foo() {
var location
getLocationName()
}
func bar() {
print(location.currentcity) // someplace
}
and call bar() from your completion handler
I am trying to figure out how to reverse geocode a CLLocation stored in CloudKit. I have the location stored in a record and I know it stores as latitude and longitude. Here's my record. The latitude and longitude appear I just took them out for now.
However I want to be able to make the location user-readable, so AKA reverse geocode it, to get the city and state. And I've looked on here so far but nothing on reverse geocoding the location I can store in CloudKit.
Here is my model:
class Peek: CloudKitSyncable {
static let kType = "Peek"
static let kPhotoData = "photoData"
static let kTimeStamp = "timestamp"
static let kTitle = "title"
static let kText = "text"
static let kLocation = "location"
static let kCity = "city"
let title: String
let text: String
let photoData: Data?
let timestamp: Date
var location: CLLocation
var comments: [Comment]
var photo: UIImage? {
guard let photoData = self.photoData else { return nil }
return UIImage(data: photoData)
}
init(title: String, timestamp: Date = Date(), text: String, photoData: Data?, comments: [Comment] = [], location: CLLocation) {
self.title = title
self.timestamp = timestamp
self.text = text
self.photoData = photoData
self.comments = comments
self.location = location
}
var recordType: String {
return Peek.kType
}
var cloudKitRecordID: CKRecordID?
convenience required init?(record: CKRecord) {
guard let timestamp = record.creationDate,
let photoAsset = record[Peek.kPhotoData] as? CKAsset,
let title = record[Peek.kTitle] as? String,
let text = record[Peek.kText] as? String,
let location = record[Peek.kLocation] as? CLLocation else { return nil }
let photoData = try? Data(contentsOf: photoAsset.fileURL)
self.init(title: title, timestamp: timestamp, text: text, photoData: photoData, location: location)
cloudKitRecordID = record.recordID
}
fileprivate var temporaryPhotoURL: URL {
let temporaryDirectory = NSTemporaryDirectory()
let temporaryDirectoryURL = URL(fileURLWithPath: temporaryDirectory)
let fileURL = temporaryDirectoryURL.appendingPathComponent(UUID().uuidString).appendingPathExtension("jpg")
try? photoData?.write(to: fileURL, options: .atomic)
return fileURL
}
}
extension CKRecord {
convenience init(_ peek: Peek) {
let recordID = CKRecordID(recordName: UUID().uuidString)
self.init(recordType: peek.recordType, recordID: recordID)
self[Peek.kTitle] = peek.title as String? as CKRecordValue?
self[Peek.kText] = peek.text as String? as CKRecordValue?
self[Peek.kTimeStamp] = peek.timestamp as CKRecordValue?
self[Peek.kLocation] = peek.location as CKRecordValue?
self[Peek.kPhotoData] = CKAsset(fileURL: peek.temporaryPhotoURL)
}
}
I also have a LocationManager file as well:
class LocationManager: NSObject {
static let sharedInstance = LocationManager()
override init() {
super.init()
locationManager.delegate = self
}
var locationManager = CLLocationManager()
var currentLocation: CLLocation?
func requestCurrentLocation() {
locationManager.requestLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.first
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error: \(error.localizedDescription)")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
}
Apple provides a method built into Core Location's CLGeocoder class. Here are the docs. If successful the completion handler will give you access to an array of CLPlacemark, so you can grab one of those and access whichever human-readable elements you need. The names of the variables are pretty generic to cover locations all over the world, so you'll have to dig in a bit to find exactly what you need. Check the docs on CLPlacemark for exact details on the variables available to you. In your particular case you'll need locality and administrativeArea for city and state, respectively.
Usage would be something like this:
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
guard let placemarks = placemarks, let placemark = placemarks.first else { return }
if let city = placemark.locality, let state = placemark.administrativeArea {
//Set your labels or whatever
}
}