手表应用与父 iphone 应用之间的通信

Communication between watch app and parent iphone app

要求:我的手表应用程序将显示来自我们服务器的最新数据。

我试过了:

为了实现这个东西,我使用了

WKInterfaceController.openParentApplication(requestDict, reply: { (returnedObject, error) -> Void in
            if (returnedObject != nil) {
//loading interface data here
}
        })

在我的应用委托函数中,我使用了

- (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 应用程序在后台 运行 时手表应用程序不显示任何内容。我调试了它,发现实际上当 iPhone 应用程序是 运行 后台时,webservice api 调用(nsurlconnection)没有重新调整任何数据,当它进入前台时,它正在回复数据以观看应用程序。

为了解决这个问题,我使用nsuserdafults 来存储数据,但问题是它并不总是显示最新数据。让我们考虑用户打开手表应用程序,它将转到父应用程序并从 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);
        }
    }
}

问题是手表应用在后台时无法从 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 告诉数据任务在 background.And 中不可用我的数据是小型 Web 服务数据,可以使用数据任务获取。所以我的服务电话不是下载任务。因此,如果 iPhone 应用程序处于后台,那么应用程序将如何获取 Web 服务数据。

我们应该使用下载任务吗?但是我猜它是用来下载任何文件的。

您需要在 iPhone 应用程序中创建一个后台任务,否则 OS 会在您的应用程序完成数据下载之前将其关闭。这里有一些文档可以提供帮助:https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

自从之前发布问答以来,情况发生了实质性变化。 openParentApplication 在 WatchOS 2 中不再可用。从好的方面来说,现在可以直接在手表上实现更多功能,根据需要从服务器更新数据。理想情况下,iPhone 应用程序还将通过一种现在可用的新通信机制同时为 WatchKit 应用程序扩展缓存最后缓存的数据,以便 WatchKit 应用程序可以显示一些内容,直到最新数据已下载,即使 iPhone 应用当前未 运行.