IOS background running for a period of time (not a map or music APP)
IOS usually cannot run in the background, especially when users click the lock screen key, the APP enters the background, and the network is immediately disconnected. How can this problem be solved? When the APP enters the background, how does the APP win time to "handle the problem ". The Code is as follows: Note: You need to define a UIBackgroundTaskIdentifier _ bgTask attribute. The code can customize how long the task will automatically end in the background.
-(Void) timerMethod :( NSTimer *) paramSender {/* process the logic required by the backend. It cannot be too long */}-(void) applicationDidEnterBackground :( UIApplication *) application {UIDevice * device = [UIDevice currentDevice]; if ([device respondsToSelector: @ selector (isMultitaskingSupported)] & [device isMultitaskingSupported]) {self. pushTimer = [NSTimer scheduledTimerWithTimeInterval: 30366f target: self selector: @ selector (timerMethod :) userInf O: nil repeats: YES]; // borrow 10 minutes from the iOS system (10 minutes by default. When you call beginBackgroundTaskWithExpirationHandler: Remember to call endBackgroundTask: method. Otherwise, iOS will terminate your program. _ bgTask = [application beginBackgroundTaskWithExpirationHandler: ^ {NSLog (@ "the background is finished in 10 minutes and the APP process is about to be suspended"); if (_ pushTimer! = Nil) {[_ pushTimer invalidate];} [application endBackgroundTask: _ bgTask]; _ bgTask = UIBackgroundTaskInvalid;}]; // if you want to end the background operation for 10 minutes in advance, logic can be added below. Currently, it is idling. dispatch_async (dispatch_get_global_queue (queue, 0), ^ {NSInteger remaining = [application backgroundTimeRemaining]; NSLog (@ "remain % d S", remaining ); while (remaining> 30 & _ bgTask! = UIBackgroundTaskInvalid) {sleep (15); remaining = [application backgroundTimeRemaining]; NSLog (@ "remain % d S", remaining); // iOS 7 is only 180 seconds, however, after this time, the program can still run // if (remaining <= 180) {// if you want to end the background running for 10 minutes in advance, open this if // [application endBackgroundTask: _ bgTask]; // _ bgTask = UIBackgroundTaskInvalid; //} NSLog (@ "background thread finished ");});}}