12.2.2. Solution
UseUiapplicationOfBeginbackgroundtaskwithexpirationhandler:Instance method. After you complete the task, callUiapplicationOfEndbackgroundtask:Method.
12.2.3. Discussion
when an IOS application is sent to the background, its main thread is paused. The thread created using the nsthread detachnewthreadselector: totar get: withobject: class method is also suspended. To complete a long-term task in the background, you must call uiapplication beginbackgroundtaskwithexpirationhandler: instance method, to IOS . the backgroundtimeremaining attribute of uiapplication contains the Program that can be used to complete his tasks. number of seconds. If a long-term task is not completed within this period, IOS terminates the program. Each call to the beginbackgroundtaskwithexpirationhandler: method must be called accordingly endbackgroundtask: method (another instance method of uiapplication ). That is to say, if you need more time to complete a task for IOS , you must tell IOS when you can complete the task. At that time, your program will iOS 5 Programming cookbook www.devdiv.com translation
DevdivTranslation:Kyelup cloudhsuPatient MokaWangli2003j3 xiebaochun dymx101 jimmylianf beyondvincent20DevdivProofread:Laigb kyelup devdivEdit:BeyondvincentVersion 1.0 | 2012 Year 07 Month 30 Day
And all of its paused threads are placed in the background.
When your program is on the frontend,UiapplicationOfBackgroundtimeremainingAttribute equalsDbl_maxConstant, which isDoubleMaximum value that can be expressed by type (equivalent to this value)IntegerUsually equal-1). InIOSIt is required to give more execution time before the program is completely suspended. This attribute specifies how many seconds the program has before it completes the task.
You can call it multiple times in a program.Beginbackgroundtaskwithexpirationhandler:Method. The important thing to remember is that whenIOSReturnsTokenOr the task id (Task identifier), You must callEndbackgroundtask:When the running task ends, it is used to mark the end of the task. If you do not,IOSWill terminate your program.
In the background, the program should neither perform full functions nor process a large amount of data. In fact, they should only complete a long-term task.
For example, a program is callingWeb Service APIAnd there is noAPIReceived response. During this period, if the program is sent to the background, it can request more time until it receives a response from the server. Once the response is received, the program must save its status and callUiapplicationOfEndbackgroundtask:The instance method marks the task as completed.
Let's look at an example. I will defineUibackgroundtaskidentifierType attribute. At the same time, Let's defineNstimerWhen the program is sent to the background, we will use it every1Seconds to output a message to the console window:
# Import <uikit/uikit. h>
@ Interface completing_a_long_running_task_in_the_backgroundappdelegate: uiresponder <uiapplicationdelegate>
@ Property (nonatomic, strong) uiwindow * window;
@ Property (nonatomic, unsafe_unretained) uibackgroundtaskidentifier backgroundtaskidentifier;
@ Property (nonatomic, strong) nstmer * mytimer;
@ End
Next, we will continue to synchronize the attributes:
# Import "completing_a_long_running_task_in_the_backgroundappdelegate.h" @ implementation completing_a_long_running_task_in_the_backgroundappdelegate
@ Synthesize window = _ window;
@ Synthesize backgroundtaskidentifier; @ synthesize mytimer;
Now, let's create a timer and start it when the program is sent to the background:
-(Bool) ismultitaskingsupported {
Bool result = no;
If ([[uidevice currentdevice]
Respondstoselector: @ selector (ismultitaskingsupported)]) {result = [[uidevice currentdevice] ismultitaskingsupported];
}
Return result;
}
-(Void) timermethod :( nstimer *) paramsender {
Nstimeinterval backgroundtimeremaining =
[[Uiapplication sharedapplication] backgroundtimeremaining];
If (backgroundtimeremaining = dbl_max) {nslog (@ "background time remaining = undetermined ");
} Else { IOS 5 Programming cookbook Www.devdiv.com Translation Arrangement
DevdivTranslation:Kyelup cloudhsuPatient MokaWangli2003j3 xiebaochun dymx101 jimmylianf beyondvincent21DevdivProofread:Laigb kyelup devdivEdit:BeyondvincentVersion 1.0 | 2012 Year 07 Month 30 Day
Nslog (@ "background time remaining = %. 02f seconds ",
Backgroundtimeremaining );
}}
-(Void) applicationdidenterbackground :( uiapplication *) Application {
If ([self ismultitaskingsupported] = No ){
Return ;}
Self. mytimer =
[Nstimer scheduledtimerwithtimeinterval: 1.0f
Target: Self
Selector: @ selector (timermethod :) userinfo: Nil
Repeats: Yes];
Self. backgroundtaskidentifier =
[Application beginbackgroundtaskwithexpirationhandler: ^ (void) {[self endbackgroundtask];
}];}
You can see that the processor of the background task (Completion Handler), We callEndbackgroundtaskMethod. This is a method we have written, as follows:
-(Void) endbackgroundtask {
Dispatch_queue_t mainqueue = dispatch_get_main_queue ();
_ Weak completing_a_long_running_task_in_the_backgroundappdelegate * weakself = self;
Dispatch_async (mainqueue, ^ (void ){
Completing_a_long_running_task_in_the_backgroundappdelegate * strongself = weakself;
If (strongself! = Nil ){
[Strongself. mytimer invalidate];
[[Uiapplication sharedapplication] endbackgroundtask: Self. backgroundtaskidentifier];
Strongself. backgroundtaskidentifier = uibackgroundtaskinvalid ;}
});}
After a long-term task is completed, we need to clear some things:
1.End All threads and timers, whether they are basic timers orGCDCreated in.
2.CallUiapplicationOfEndbackgroundtask:Method to end the background task.
3.Set the task idUibackgroundtaskinvalid, Marking the end of our task.
Finally, when our application returns to the foreground, if our background task is still being executed, we need to ensure that we are killing it:
-(Void) applicationwillenterforeground :( uiapplication *) Application {
If (self. backgroundtaskidentifier! = Uibackgroundtaskinvalid ){
[Self endbackgroundtask];}
}
In our example, whenever a program is sent to the backend, we will require more time to complete a long-term task (for example, here is our timerCode). During our time, we constantly readUiapplicationInstanceBackgroundtimeremainingProperty value to print it to the console. InUiapplicationOfBeginbackgroundtask withexpirationhandler:In the instance method, the code we provide will be executed before a long-term task is completed in the additional time of the Program (version 1 is probably before the task expires5To10Seconds ). Here, we only need to callUiapplicationOfEndbackgroundtask:Instance method to end the task.