OpenParentApplication only works when the application is in the foreground

I try to request data from the server using openParentApplicationand use it in the clock extension, but I get nothing when the main application does not work in the foreground. When the main application runs in the foreground, everything works fine.

+4
source share
2 answers

I had this problem before, and the reason is that you did not register a long background operation, and the system killed it. Here is how I sorted it, please see Comments for an explanation, this is all in the AppDelegate file, and it’s quick, but you can easily transfer it to 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()
    }
}
+10
source

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();
    });
};
+2

All Articles