我尝试使用{{1}}从服务器请求数据并在手表扩展程序中使用它,但当主应用程序未在前台运行时,我无法获得任何回复。当主应用程序在前台运行时,一切正常。
答案 0 :(得分:10)
之前我遇到过此问题,原因是您没有注册长时间运行的后台操作,系统会将其终止。 这就是我对此进行排序的方法,请参阅注释的注释,这些都在AppDelegate文件中,并且在swift中,但您可以轻松地将其移植到Objective-c:
private var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
func registerBackgroundTask() {
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
[unowned self] in
self.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
// MARK: - Watch Kit
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
registerBackgroundTask()
// Fetch the data from the network here
// In the competition handler you need to call:
// the nil can be replaced with something else you want to pass back to the watch kit
reply(nil)
if self.backgroundTask != UIBackgroundTaskInvalid {
self.endBackgroundTask()
}
}
答案 1 :(得分:2)
只是添加了一些Obj-c等效的东西,尽管我使用的是直接GCD,所以它的方法略有不同。
__block UIBackgroundTaskIdentifier identifier = UIBackgroundTaskInvalid;
dispatch_block_t endBlock = ^ {
if (identifier != UIBackgroundTaskInvalid) {
[application endBackgroundTask:identifier];
}
identifier = UIBackgroundTaskInvalid;
};
identifier = [application beginBackgroundTaskWithExpirationHandler:endBlock];
reply = ^(NSDictionary *replyInfo) {
reply(replyInfo);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
endBlock();
});
};