我对 Watchkit/iOS 应用程序通信有点困惑。这就是我想要做的
- 按 watch 上的按钮
- 获取当前 GPS 位置(通过手机)
- 使用 GPS 位置进行后端调用
- 在 watch 上展示后端结果
我想我在 WKInterfaceController.openParentApplication 和 handleWatchKitExtensionRequest 方面走在了正确的轨道上,但我该如何进行异步调用?
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/