0

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

Pooja Mishra
  • 17
  • 1
  • 8

2 Answers2

0

You will need call beginBackgroundTask before you start an asynchronous network operation in the background

0

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
    }