要求:My Watch 应用程序将显示来 self 们服务器的最新数据。
我试过了:
为了实现这个东西我用了
WKInterfaceController.openParentApplication(requestDict, reply: { (returnedObject, error) -> Void in
if (returnedObject != nil) {
//loading interface data here
}
})
在我的应用委托(delegate)函数中我使用了
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {
// doing web service call using asynchronous nsurlconnection and replying with response dictionary
}
问题: 问题是当 iPhone 应用程序在前台时应用程序运行良好,但当 iPhone 应用程序在后台运行时 watch 应用程序不显示任何内容。我对其进行了调试,发现实际上当 iPhone 应用程序在后台运行时,web 服务 api 调用(nsurlconnection)没有返回任何数据,当它进入前台时,它正在回复数据以观看应用程序。
为了解决这个问题,我使用 nsuserdafults 来存储数据,但问题是它并不总是显示最新数据。让我们考虑用户打开 watch 应用程序,它将转到父应用程序并从 userdafults 返回旧数据。
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {
if ([userInfo[@"type"] isEqualToString:@"list"]) {
[self fetchWatchData];//it will get and store data when app will be foreground
NSDictionary *replyDict = [UtiltiyManager getWatchData];//data from userdefaults
if (replyDict) {
reply(replyDict);
}else {
NSDictionary *noDataDict = @{@"data":@"nodata"};
reply(noDataDict);
}
}
}
问题是 watch 应用程序在后台时无法从 iphone 获取最新数据。由于没有可在后台运行的服务调用 api。我检查了 NSURLConnection 和 NSURLSessionDataTask 都是前台 api 调用。
任何解决方案或想法?
更新 1:
Apple 文档说:
Types of Tasks Within a session, the NSURLSession class supports three types of tasks: data tasks, download tasks, and upload tasks.
Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests from your app to a server. Data tasks can return data to your app one piece at a time after each piece of data is received, or all at once through a completion handler. Because data tasks do not store the data to a file, they are not supported in background sessions. Download tasks retrieve data in the form of a file, and support background downloads while the app is not running. Upload tasks send data (usually in the form of a file), and support background uploads while the app is not running.
Apple 告诉数据任务在后台不可用。我的数据是小型 Web 服务数据,可以使用数据任务获取。所以我的服务电话不是下载任务。因此,如果 iPhone 应用程序在后台运行,那么应用程序将如何获取 Web 服务数据。
我们应该使用下载任务吗?但我猜它的目的是下载任何文件。
最佳答案
您需要在 iPhone 应用程序中创建一个后台任务,否则操作系统会在您的应用程序完成下载数据之前终止您的应用程序。这里有一些文档可以提供帮助:https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
关于ios - watch app和父iphone app之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30090410/