ios - Swift semaphore not waiting for function to finish before calling UI -
i'm trying delay segue until response reversegeocodelocation
call. however, when using breakpoints check when value changes, it's still happening after ui transition occurs. i've tried having function void , current string
return.
edited code:
func getreversedgeocodelocation(completionhandler: (string, nserror?) ->()) { let semaphore = dispatch_semaphore_create(0) dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0)) { () -> void in clgeocoder().reversegeocodelocation(self.newmeetuplocation, completionhandler: {(placemarks, error) -> void in if error != nil { print("reverse geocoder failed error" + error!.localizeddescription) return } else if placemarks?.count > 0 { } else { print("problem data received geocoder") } completionhandler(placemarks!.first!.name! ?? "", error) }) dispatch_semaphore_signal(semaphore) } dispatch_semaphore_wait(semaphore, dispatch_time_forever) }
old code:
let semaphore = dispatch_semaphore_create(1) //even 0, it's not working dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0)) { () -> void in self.newaddress = self.getreversedgeocodelocation() dispatch_semaphore_signal(semaphore) } dispatch_semaphore_wait(semaphore, dispatch_time_forever) //dispatch_semaphore_signal(semaphore) print(self.newaddress + ".") self.performseguewithidentifier("maintonewaddress", sender: self) func getreversedgeocodelocation() -> string{ var address = "" clgeocoder().reversegeocodelocation(self.newaddresslocation, completionhandler: {(placemarks, error) -> void in if error != nil { print("reverse geocoder failed error" + error!.localizeddescription) return } else if placemarks?.count > 0 { let pm = placemarks?.first! address = pm!.name! } else { print("problem data received geocoder") } }) return address }
using semaphore , dispatching call getreversedgeocodelocation
unnecessarily complicated. clgeocoder().reversegeocodelocation
asynchronous. if pass completion handler closure getreversedgeocodelocation
can use invoke segue;
self.getreversedgeocodelocation(self.newaddresslocation, completionhandler: { (address,error) in guard error == nil else { print("reverse geocoder failed error" + error!.localizeddescription) return } guard let address = address else { print("no address returned") return } self.newaddress = address dispatch_async(dispatch_get_main_queue(), { self.performseguewithidentifier("maintonewaddress", sender: self) }) }) func getreversedgeocodelocation(addresslocation: string, completionhandler:((address: string?, error: nserror?) -> void))) { clgeocoder().reversegeocodelocation(self.newaddresslocation, completionhandler: {(placemarks, error) -> void in var address = nil if placemarks.count > 0 { if let pm = placemarks!.first { address = pm.name } } else { print("problem data received geocoder") } completionhandler(address,error) }) }
Comments
Post a Comment