我试图通过使用openParentApplication
从服务器请求数据并将其用在watch扩展中,但当主应用程序未运行时我没有收到任何回应在前台。当主应用程序在前台运行时,一切正常。openParentApplication只适用于应用程序在前台运行时
4
A
回答
10
我之前有过这个问题,原因是您还没有注册长时间运行的后台操作,系统将其杀死。 这是我整理这一点,请参阅解释的意见,这是所有的AppDelegate文件并将其迅速,但你可以很容易地移植到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()
}
}
2
只是增加了一些对象 - 相当于该做到这一点,虽然我的直接使用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();
});
};
相关问题
- 1. 让应用程序在前台运行
- 2. 如何在iOS应用程序处于前台时在后台运行操作
- 3. 测距信标只适用于应用程序运行?
- 4. Android:应用程序在后台或前台运行? :S
- 5. 适用于Linux的C应用程序的运行时配置
- 6. 当应用程序未运行时在后台运行SyncAdapter
- 7. 在前台和后台运行一个应用程序(时间共享)
- 8. onMessageReceived()在应用程序处于前台时未调用
- 9. 只有当应用程序在前台时,Toast才会出现?
- 10. 使用Swift在应用程序在前台运行时显示推送通知
- 11. 在后台运行应用程序IntentService
- 12. Android应用程序在后台运行
- 13. Android,在后台运行应用程序
- 14. 在后台运行应用程序
- 15. 在后台运行应用程序
- 16. 在后台运行iOS应用程序
- 17. 在后台运行的应用程序
- 18. iphone应用程序在后台运行?
- 19. Android在后台运行应用程序
- 20. 在后台运行应用程序Cordova
- 21. 在后台运行android应用程序?
- 22. 在后台运行应用程序
- 23. 在后台运行应用程序
- 24. 在后台运行应用程序?
- 25. WatchOS应用程序在后台运行
- 26. 在后台运行应用程序android
- 27. 应用程序处于后台时运行CLLocation
- 28. 用于在后台运行应用程序的脚本脚本
- 29. 将应用程序置于前台
- 30. iPhone - 在应用程序在后台运行时更改应用程序设置
非常感谢你的通信现在工作,但是当应用程序没有在前台运行我得到这个错误:**的iPhone应用程序从来没有所谓的回复()** –
@mohammedalwaili确保您拨打的回复(无),从你的比赛处理者,也如果你有其他处理失败。您必须从应用程序handleWatchKitExtensionRequest中针对每种可能的方案调用reply(nil):成功/失败。 – Greg
非常感谢您的帮助,现在一切正常。 –