ios - 如何使用 Watchkit 进行异步操作(GPS + API 调用)和

标签 ios swift watchkit apple-watch

我对 Watchkit/iOS 应用程序通信有点困惑。这就是我想要做的

  1. 按 watch 上的按钮
  2. 获取当前 GPS 位置(通过手机)
  3. 使用 GPS 位置进行后端调用
  4. 在 watch 上展示后端结果

我想我在 WKInterfaceController.openParentApplicationhandleWatchKitExtensionRequest 方面走在了正确的轨道上,但我该如何进行异步调用?

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([:])
    }

最佳答案

好的,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([:])

关于ios - 如何使用 Watchkit 进行异步操作(GPS + API 调用)和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29455929/

相关文章:

ios - 手腕掉落后用户通知未出现在 watch 上

ios - 在registerUserNotificationSettings之后立即调用registerForRemoteNotifications?

ios - 仅使用 FB 和 Twitter 标志而不是它们的功能

ios - 无法让 UIScrollView 在 UITableViewCell 内部被识别,nil 错误

ios - 只更新一次位置

ios - Swift 中的可选动态属性

ios - Return Observer.create 不返回并且旁边的代码不能使用 RxSwift 工作

ios - 如何防止 FetchRequest 观察关系的变化?

Watchkit密码按钮按下检测

ios - 从通知中心打开推送时 Apple Watch : dynamic Long Look not shown,