【发布时间】:2016-05-25 02:20:53
【问题描述】:
我正在尝试延迟转场,直到我收到来自 reverseGeocodeLocation 电话的回复。但是,当使用断点检查值何时实际更改时,它仍然会在 UI 转换发生后发生。我尝试过让函数为 void 并使用当前的 String 返回。
编辑代码:
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 with error" + error!.localizedDescription)
return
}
else if placemarks?.count > 0 {
}
else {
print("Problem with the data received from geocoder")
}
completionHandler(placemarks!.first!.name! ?? "", error)
})
dispatch_semaphore_signal(semaphore)
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
旧代码:
let semaphore = dispatch_semaphore_create(1) //even with 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 with error" + error!.localizedDescription)
return
}
else if placemarks?.count > 0 {
let pm = placemarks?.first!
address = pm!.name!
}
else {
print("Problem with the data received from geocoder")
}
})
return address
}
【问题讨论】:
-
(1) 您应该使用 count = 0 创建信号量。(2) 可能是您的
getReversedGeocodeLocation()本身是异步的? -
使用信号量是不必要的复杂。只需将完成闭包传递给
getReversedGeocodeLocation并从reverseGeocodeLocation的完成处理程序调用该闭包;让闭包执行转场 -
您在上述函数中的信号量是无用的。如果您要使用信号量“等待”,为什么还要分派异步。您可以使用
reverseGeocodeLocation上的信号量来使其同步。 -
是的,一旦你让我回顾我最初使用它的原因,我就意识到这毫无意义。我编辑了我的代码,它仍然无法正常工作,但我希望它朝着正确的方向发展
-
@brandon 不确定这是否是一个可能的问题,但是当我的
CLGeocoder().reverseGeocodeLocation和dispatch_semaphore_wait有断点时,前者在线程 10 中,后者在线程 1 中
标签: ios swift mapkit semaphore