0

I want to make an application that updates users location to my remote server in every xx minute, even the application is in background I have tried the following code

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    i=0;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
        [app endBackgroundTask:bgTask]; 
        bgTask = UIBackgroundTaskInvalid;
    }];
    bgTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundTask:) userInfo:nil repeats:YES];

}

-(void)backgroundTask:(NSTimer*)timer{

    i++;
    NSLog(@"%s  %d",__func__,i);
}

But the timer callback stops after around 10 minutes How can I make an application that continuously updates current location to my server

Johnykutty
  • 12,091
  • 13
  • 59
  • 100

2 Answers2

3

You're probably missing the Background Modes key in your app's Info.plist file:

<key>UIBackgroundModes</key>
    <array>
            <string>location</string>
    </array>

This lets your app access location services while in the background.

But, this type of thing has been asked many times, so also do a little browsing of other stack overflow questions for more information.

Here's another one to read.

Community
  • 1
  • 1
Nate
  • 31,017
  • 13
  • 83
  • 207
0

You can update in background only for 3 minutes.Set Capabilities-> BackgroundFetch on for more or equal than 3 fields using following code

Call this didenterbackground or foreground

var time = 120
func applicationDidEnterBackground(_ application: UIApplication)
    {
        time = 180
        self.doBackgroundTask()
    }

 var timerBack  = Timer()
    func doBackgroundTask() {

        DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
            self.beginBackgroundUpdateTask()


            self.timerBack = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.displayAlert), userInfo: nil, repeats: true)
            RunLoop.current.add(self.timerBack, forMode: RunLoopMode.defaultRunLoopMode)
            RunLoop.current.run()

            self.endBackgroundUpdateTask()
        }
    }
    var backgroundUpdateTask: UIBackgroundTaskIdentifier!

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

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

//Do whatever you want

func displayAlert{


}