swift中void函数中的dispatch_async和意外的非void返回值
我的appDelegate
中有一个函数返回用户的当前位置。
现在我想在其他地方异步调用它,我做了:
func handleLocation() -> CLLocation { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.startGPS() while (!appDelegate.isLocationFixed()) { sleep(1) } dispatch_async(dispatch_get_main_queue()) { return appDelegate.getLocation() } } }
但现在这行return appDelegate.getLocation()
给我带来错误:
void函数中出现意外的非void返回值
我对Swift
线程不太了解,你能帮我解决这个问题吗?
问题是
dispatch_async(dispatch_get_global_queue(priority, 0)) {
和
dispatch_async(dispatch_get_main_queue()) {
实际上是创建闭包/函数,因此其中的任何代码都与该函数相关,而不是
func handleLocation() -> CLLocation {
如果在函数内进行异步操作,则异步操作完成后,实际上不能有return语句。 相反,您应该在函数中使用完成处理程序。 例如:
func aSyncFunction(completionHandler: (AnyObject) -> ()) { //do async opporation completionHandler("finished") // call the completion block when finished }
以下是我将如何为您的用例实现它:
func handleLocation(completionBlock: (CLLocation?) -> ()) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { guard let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate else { dispatch_async(dispatch_get_main_queue()) { completionBlock(nil) } return } appDelegate.startGPS() while (!appDelegate.isLocationFixed()) { sleep(1) } dispatch_async(dispatch_get_main_queue()) { completionBlock(appDelegate.getLocation()) } } }
示例用法:
handleLocation { (location: CLLocation?) in if let location = location { //use valid location } }
- keyboardWillShow被其他应用程序的键盘调用
- iOS打印不允许UIPrintInteractionController出现
- iOS:应用程序在安装应用程序时不会询问用户的权限。 每次都得到kCLAuthorizationStatusNotDetermined – Objective-c&Swift
- 通过CKSubscription观察CKRecord删除不起作用
- 我可以在iPad上使用哪种UIKeyboardType
- 检测轻拍的字符。 UITextView characterRangeAtPoint总是返回nil
- UIView框架更改通知
- UIPickerViewselect并隐藏
- 我怎样才能加载一个本地的HTML文件,而不是在Xcode的web视图的网页?