IOS program back to the background, how to continue to perform tasks

Source: Internet
Author: User

When the program is retired from the foreground, the program's delegate method is executed.

-(void) Applicationdidenterbackground: (uiapplication *) application

{

}

Problem: When the app is sent to the background, the main thread is paused. The thread created with the Nsthread Detachnewthreadselector:totar Get:withobject: Class method is also suspended. Scenario: The app executes the agent method Applicationdidenterbackground from the foreground back to the daemon. At this point, we have only a short time to deal with the work that needs to be handled, and then all the threads are suspended. In fact, we need more time to do the necessary things for our needs: for example:

1. Save the data to the remote server operation.

2. Record some of the required information operations.

Reference Solutions:apply to iOS, complete a long-running task task in the background

1. In the project's AppDelegate.h file

Declaring a uibackgroundtaskidentifier is equivalent to writing a promissory note. Tell iOS that our program will take more time to completelong-running TaskTask.

@property (nonatomic, unsafe_unretained) Uibackgroundtaskidentifier backgroundtaskidentifier;

@property (nonatomic, strong) Nstimer *mytimer;

2. In the project's APPDELEGATE.M file1. Note The process of completing the IOU in the Applicationdidenterbackground methodThat is: self. Backgroundtaskidentifier =[application beginbackgroundtaskwithexpirationhandler:^ (void) {

[Self endbackgroundtask];

}];

This method is executed when the application falls into the background

-(void) Applicationdidenterbackground: (uiapplication *) application

{

Use this method to free up public resources, store user data, stop our defined timers (timers), and store relevant information before the program terminates.

If our application provides a way to execute in the background, this method will replace the execution of the Applicationwillterminate method when the program exits.

Mark a long-running background task to begin

By debugging, we found that iOS gave us 10 minutes (600s) to perform this task.

Self.backgroundtaskidentifier =[application beginbackgroundtaskwithexpirationhandler:^ (void) {

The block block will be executed when the application leaves the backend at the end of the day (the time the application leaves the background to execute is limited)

We need to do some cleanup work in block blocks.

If the cleanup fails, it will cause the program to hang

Cleanup work needs to be done synchronously in the main thread

[Self endbackgroundtask];

}];

Simulating a long-running Task

Self.mytimer =[nstimer scheduledtimerwithtimeinterval:1.0f

Target:self

Selector: @selector (timermethod:) userinfo:nil

Repeats:yes];

}

2. After completion, to tell iOS, the task completed, submit the completion of the application "good to Borrow good":

[[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskIdentifier];

Strongself.backgroundtaskidentifier = Uibackgroundtaskinvalid;

}

});

-(void) endbackgroundtask{

dispatch_queue_t mainqueue = Dispatch_get_main_queue ();

Appdelegate *weakself = self;

Dispatch_async (mainqueue, ^ (void) {

Appdelegate *strongself = weakself;

if (strongself! = nil) {

[Strongself.mytimer invalidate];//Stop Timer

For each call to the Beginbackgroundtaskwithexpirationhandler: method, the Endbackgroundtask: method must be called accordingly. So, to tell the application that you've done it.

That is, we need more time for iOS to complete a task, so we have to tell iOS when you can finish that task.

That is to tell the application: "Good to borrow good".

Mark the specified background task complete

[[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskIdentifier];

Destroying background task identifiers

Strongself.backgroundtaskidentifier = Uibackgroundtaskinvalid;

}

});

}

A long-running Task method for simulation

-(void) Timermethod: (Nstimer *) paramsender{

The Backgroundtimeremaining property contains the time that the program left for us

Nstimeinterval backgroundtimeremaining =[[uiapplication sharedapplication] backgroundtimeremaining];

if (backgroundtimeremaining = = Dbl_max) {

NSLog (@ "Background time Remaining = undetermined");

} else {

NSLog (@ "Background time Remaining =%.02f Seconds", backgroundtimeremaining);

}

}

3. Remember, borrowing and swapping must be paired! The specific explanation, I also wrote in the method, if has the mistake place, also hoped can correct me! Thank you!4. If the program is completed ahead of time, you can also end it early:

[[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskIdentifier];

Self.backgroundtaskidentifier = Uibackgroundtaskinvalid;

apply to iOS, unlimited time in the backgroundIt is proven that even when performing long-running task tasks, there is a time limit when the program is transferred to the background. Generally 10 points (600s). How to apply for unlimited time to the program?! Then cheat on the iOS system. Make it feel like your program is still running. Then play an audio file in the background with Avaudioplayer Infinite loop. Hehe, if play a audio file without sound?!! Steps:1. Add background playback support to the Plish file. Added: Required background modes. and set to: Audio2. Initialize a avaudioplayer audio and play it without any restrictions.

-(void) viewdidload

{

[Super Viewdidload];

dispatch_queue_t dispatchqueue = dispatch_get_global_queue (dispatch_queue_priority_default, 0);

Dispatch_async (dispatchqueue, ^ (void) {

Nserror *audiosessionerror = nil;

Avaudiosession *audiosession = [Avaudiosession sharedinstance];

if ([Audiosession setcategory:avaudiosessioncategoryplayback Error:&audiosessionerror]) {

NSLog (@ "Successfully set the audio session.");

} else {

NSLog (@ "Could not set the audio session");

}

NSBundle *mainbundle = [NSBundle mainbundle];

NSString *filepath = [Mainbundle pathforresource:@ "Mysong" oftype:@ "MP3"];

NSData *filedata = [NSData Datawithcontentsoffile:filepath];

Nserror *error = nil;

Self.audioplayer = [[Avaudioplayer alloc] Initwithdata:filedata error:&error];

if (self.audioplayer! = nil) {

Self.audioPlayer.delegate = self;

[Self.audioplayer setnumberofloops:-1];

if ([Self.audioplayer preparetoplay] && [Self.audioplayer play]) {

NSLog (@ "successfully started playing ...");

} else {

NSLog (@ "Failed to play.");

}

} else {

}

});

}

IOS program back to the background, how to continue to perform tasks

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.