2015-04-05 101 views
1

我对Watchkit/iOS应用程序通信有点困惑。这就是我要做的如何使用Watchkit进行异步操作(GPS + API调用)和

  1. 按下一个按钮上的手表
  2. 获得的(通过电话)
  3. 请与GPS定位
  4. 目前后端结果的后端调用当前GPS位置对手表

我想我在正确的轨道上WKInterfaceController.openParentApplicationhandleWatchKitExtensionReque st但我怎样才能做异步调用?

func application(application: UIApplication!, 
     handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, 
     reply: (([NSObject : AnyObject]!) -> Void)!) { 

      // 1 
      if let request = userInfo["request"] as? String { 
       if request == "refreshData" { 

        var backendService = BackendService() 
        var locationManager = LocationManager() 
        locationManager.updateLocation() 

        // How to wait for location manager to get lat/long? 

        backendService.makeAFantasticCAll(locationManager.latitude, longitude: locationManager.longitude) 

        // How to wait for result? Should i use a delegate? How can i fire reply() in this delegate? 

        // 3 
        reply(["result": NSKeyedArchiver.archivedDataWithRootObject(result)]) 

        return 
       } 
      } 

      // 4 
      reply([:]) 
    } 

回答

0

好的,nestedCompletion处理程序是一种解决方案(但很难读)

func application(application: UIApplication!, 
    handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, 
    reply: (([NSObject : AnyObject]!) -> Void)!) { 

    if let request = userInfo["request"] as? String { 

     if request == "refreshData" { 

      // Get GPS Location 
      var locationManager = LocationManager.sharedInstance 
      locationManager.startUpdatingLocationWithCompletionHandler { (latitude, longitude, status, verboseMessage, error) ->() in 

       // Call backend 
       var backendService = BackendService() 
       backendService.makeAFantasticCAll(latitude, longitude: longitude) { (result:Result?, error:String?) ->() in 

        if let title: String = result?.title { 
         reply(["title": title]) 
        } 

       } 

      } 

      return 
     } 
    } 

    reply([:]) 

}