繁体   English   中英

openParentApplication仅在应用程序在前台运行时才有效

[英]openParentApplication only works when the app is running in the foreground

我正在尝试使用openParentApplication从服务器请求数据并在watch扩展中使用它,但是当主应用程序没有在前台运行时我没有得到任何回复。 当主应用程序在前台运行时,一切正常。

之前我遇到过这个问题,原因是你没有注册长时间运行的后台操作,系统将其终止。 这就是我对此进行排序的方法,请参阅注解说明,这些都在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()
    }
}

只是添加了一些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();
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM