ios - Swift 中 void 函数中的 dispatch_async 和意外的非 void 返回值

标签 ios swift dispatch-async

我的 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() 给我带来了错误:

unexpected non-void return value in void function

我还不太了解 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
    }
}

关于ios - Swift 中 void 函数中的 dispatch_async 和意外的非 void 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338437/

相关文章:

ios - asyncAfter 似乎没有时间延迟 - Swift

swift - 我需要在 main_queue 上哪里使用dispatch_async?

ios - Swift 错误 : cannot invoke `dataWithRequest` with an argument list of type `(NSURL, completionHandler :(_, _,_) -> Void

ios - Xml 解析器委托(delegate)未在 Swift 中调用

ios - 如何避免 viewWillAppear 最初调用

javascript - 当 HTML 页面在 iOS 应用程序的 WKWebView 或 UIWebView 中运行时,使用 getUserMedia 录制音频?

ios - 在调用 UITapGestureRecognizer 函数之前取消初始化

ios - 异步 swift 3

ios - MVYSideMenu 在所有 View Controller iOS 中使用导航 Controller

ios - 为表格 View 单元格图像创建圆形图片