IOS solves the problem of timer and location update stop after the app enters the background. ios Timer

Source: Internet
Author: User

IOS solves the problem of timer and location update stop after the app enters the background. ios Timer

Because the iOS system runs in "pseudo-background" mode, when you press the HOME key, if the program does not perform any operation, the application will have 5 seconds of execution buffer time, and the random program will be suspended, all Task terminals, including timer and location update operations. However, after the background mode switch is enabled, some tasks can be executed in the background, such as audio, location, Bluetooth, download, VOIP, even so, the background running of the program can be extended by a maximum of 594 seconds (about 10 minutes ). Unfortunately, after declaring the background mode, the program is likely to be rejected when the app is mounted. Based on this, I have developed a method that allows the timer and positioning to continue running when the app enters the foreground without declaring the background mode.

The implementation principle is as follows:

Use the iOS notification mechanism to send a notification when the program enters the background and returns to the foreground again. Record the current time when the program enters the background and the current time when the program returns to the foreground again, and calculate the time interval between the two, add the notification listener wherever the program needs it and execute the code block in the listening method. The parameters in the code block are the notification object and the calculated time interval. Take the timer as an example. After the program enters the background, the timer stops running. In this case, the content in the code block is executed when the program returns back to the foreground, when the program enters the background, the current time interval of the timer and the time interval parameter of the code block can make the timer time accurately. Not much nonsense. Go to the Code:

In the AppDelegate. m implementation file:

- (void)applicationDidEnterBackground:(UIApplication *)application {    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.    [[NSNotificationCenter defaultCenter]postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil];}- (void)applicationWillEnterForeground:(UIApplication *)application {    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.    [[NSNotificationCenter defaultCenter]postNotificationName:UIApplicationWillEnterForegroundNotification object:nil];}

Code Description: after the program enters the background, the system notification mechanism is used to notify the program to enter the background and return to the foreground again. The Listener object is all objects.

Then define the class YTHandlerEnterBackground for a processing program to enter the background.

/// YTHandlerEnterBackground. h // time-sharing lease // Created by Ke qipu on 17/2/24. // Copyright: Ke qipu in December 2017. all rights reserved. // # import <Foundation/Foundation. h> # import <UIKit/UIKit. h>/** enter the background block typedef */typedef void (^ YTHandlerEnterBackgroundBlock) (NSNotification * _ Nonnull note, NSTimeInterval stayBackgroundTime ); /** processing enters the background and calculates the time interval class left in the background */@ interface YTHandlerEnterBackground: NSObject/** Add the observer and process the background */+ (void) addObserverUsingBlock :( nullable YTHandlerEnterBackgroundBlock) block;/** remove the background observer */+ (void) removeNotificationObserver :( nullable id) observer; @ end

In the YTHandlerEnterBackground. m implementation file:

 

/// YTHandlerEnterBackground. m // time-sharing lease // Created by Ke qipu on 17/2/24. // Copyright: Ke qipu in December 2017. all rights reserved. // # import "YTHandlerEnterBackground. h "@ implementation YTHandlerEnterBackground + (void) addObserverUsingBlock :( partial) block {_ block CFAbsoluteTime enterBackgroundTime; [[nsicationicationcenter defacenter center] addObserverForName: Listener On object: nil queue: nil usingBlock: ^ (NSNotification * _ Nonnull note) {if (! [Note. object isKindOfClass: [UIApplication class]) {enterBackgroundTime = Response () ;}}]; _ block CFAbsoluteTime enterForegroundTime; [[nsicationicationcenter defacenter center] addObserverForName: Response object: nil queue: nil usingBlock: ^ (NSNotification * _ Nonnull note) {if (! [Note. object isKindOfClass: [UIApplication class]) {enterForegroundTime = CFAbsoluteTimeGetCurrent (); CFAbsoluteTime timeInterval = enterForegroundTime-enterBackgroundTime; block? Block (note, timeInterval): nil ;}] ;}+ (void) removeNotificationObserver :( id) observer {if (! Observer) {return;} [[nsicationcenter center defacenter center] removeObserver: observer name: jsonobject: nil]; [[NSNotificationCenter defacenter center] removeObserver: observer name: UIApplicationWillEnterForegroundNotification object: nil];} @ end

 

This class is implemented to add a notification listener and process the background and remove the notification listener. Note that in the addObserverUsingBlock method, if (! [Note. object isKindOfClass: [UIApplication class]). Otherwise, the code block in the addObserverForName method will be executed multiple times. This code is executed twice. The addObserverUsingBlock method is to call the viewWillAppear method to add a notification listener and call the method to remove the notification listener in the viewWillDisappear method.

 

For example, when the timer NSTimer controller is used:

- (void)viewWillAppear:(BOOL)animated {    [super viewWillAppear:animated];    [YTHandlerEnterBackground addObserverUsingBlock:^(NSNotification * _Nonnull note, NSTimeInterval stayBackgroundTime) {        self.rentTimerInterval = self.rentTimerInterval-stayBackgroundTime;    }];}- (void)viewWillDisappear:(BOOL)animated {    [super viewWillDisappear:animated];    [self.timer invalidate];    [YTHandlerEnterBackground removeNotificationObserver:self];}

I defined a timer object timer attribute with a 5-minute countdown, and defined a timer current countdown interval timerinterval attribute. In the Add notification listener code block, rentTimerInterval is equal to the countdown interval when you enter the background minus the interval when the program stays in the background. When the timer returns to the foreground again, the timer interval at this time continues. Although the timer does not run continuously in the background, this method is also used to implement the correct and real-time timer.

 

Similarly, when the program has the location update function, when the program enters the background, the location service object will automatically stop the update. At this time, the above two processing methods will still be called to enter the background, after the program enters the background, start locating again:

In the class to be updated:

 

-(Void) viewWillAppear :( BOOL) animated {[super viewWillAppear: animated]; self. locService. delegate = self; [self. locService startUserLocationService]; // enter the background and then go to the foreground to locate [YTHandlerEnterBackground addObserverUsingBlock: ^ (NSNotification * _ Nonnull note, NSTimeInterval stayBackgroundTime) {[self. locService startUserLocationService];}-(void) viewWillDisappear :( BOOL) animated {[super viewWillDisappear: animated]; // stop locating self. locService. delegate = nil; [self. locService stopUserLocationService]; // remove the background listener [YTHandlerEnterBackground removeNotificationObserver: self];}

Baidu map SDK is used here

 

This method can be used for tasks that need to be run in the background, such as timer and location update, but the trouble is that, you need to call these two methods in any required classes. You can use them as needed, add other parameters when the program enters the background and returns to the foreground again (Notification object parameters are required), for example, save the operations before entering the background. Or define different methods to add notification listeners to meet different requirements.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.