简体   繁体   中英

How can I do an action on receiving a remote notification even when the app is in background or terminated?

I have used this function:

 func application(_ application: UIApplication,  didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)

but getting no result. Also I have added the required capabilities(refer screenshot for this). How can I do it? Actually I have to send the device's location to the server when the app receives notification. I am able to do it when the app is in foreground but not when the app is in background or is terminated. screenshot

在后台启动异步网络操作之前​​,需要先调用beginBackgroundTask

Objective

Use this code: here type of backgroundUpdateTask variable is NSInteger

- (void) doUpdate 
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [self beginBackgroundUpdateTask];

        NSURLResponse * response = nil;
        NSError  * error = nil;
        //call your api here for location update
        NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];

        // Do something with the result

        [self endBackgroundUpdateTask];
    });
}
- (void) beginBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

Swift

func doUpdate() {
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            self.beginBackgroundUpdateTask()
            var response: URLResponse? = nil
            var error: Error? = nil
            //call your api here for location update
            let responseData: Data? = try? NSURLConnection.sendSynchronousRequest(request, returning: response)
            // Do something with the result
            self.endBackgroundUpdateTask()
        })
    }

    func beginBackgroundUpdateTask() {
        backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {() -> Void in
            self.endBackgroundUpdateTask()
        })
    }

    func endBackgroundUpdateTask() {
        UIApplication.shared.endBackgroundTask(backgroundUpdateTask)
        backgroundUpdateTask = UIBackgroundTaskInvalid
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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