During IOS application and game development, we often need to perform operations when users switch to the background, such as clearing the memory or saving user data. These operations are generally performed in
Applicationdidenterbackground of appdelagate :(Uiapplication*) In the application (of course, we can alsoReceive applicationsProgramThe notification uiapplicationdidenterbackgroundnotification is sent to trigger processing.). However, these work systems only allocate five seconds for processing. Otherwise, the system will force the application to exit. Therefore, in many cases, we need to apply for more time to process related background operations.
Now let's take a look at how to apply for more background time.CodeAs follows:
-(Void) Applicationdidenterbackground :(Uiapplication*) Application
{
Uiapplication* APP = [Uiapplicationsharedapplication];
//A background task identifier
_ BlockUibackgroundtaskidentifierTaskid;
//Apply For more background running time
Taskid = [AppBeginbackgroundtaskwithexpirationhandler: ^ (Void){
//Execution beyond the extended system time
Nslog(@ "Background task ran out of time and was termined .");
[AppEndbackgroundtask: Taskid];
}];
//Application failed
If(Taskid =Uibackgroundtaskinvalid){
Nslog(@ "Fail to start background task! ");
Return;
}
Nslog(@ "Starting background task with % F seconds remaining", App.Backgroundtimeremaining);
While(True){
[Nsthreadsleepfortimeinterval: 1];
Nslog(@"Ding in the background");
}
}
I think the code has been commented out clearly. when running the code, we will find that the system gives us an extended period of nearly 600 s. Of course, this is enough for us to clean up memory and save user information.