After the program is sent to the background, borrow time from IOS to complete long-term tasks-prepare

Source: Internet
Author: User
Tags uikit

12.2.2. Programme

Use UIApplication's Beginbackgroundtaskwithexpirationhandler: Instance method. After you complete the task, call UIApplication's Endbackgroundtask: method.

12.2.3. Discussion

When an iOS app is sent to the background, its main thread is paused. You use the Nsthread detachnewthreadselector:totar get:withobject: The thread created by the class method is also suspended. If you want to complete a long-term task in the background, you must call UIApplication's Beginbackgroundtaskwithexpirationhandler: instance method to borrow some time from iOS. The Backgroundtimeremaining property of UIApplication contains the number of seconds that the program can use to complete his task. If the long-term task is not completed during this period, iOS will terminate the program. For each call to the Beginbackgroundtaskwithexpirationhandler: method, the Endbackgroundtask: Method (another instance method of UIApplication) must be called accordingly. That is, if you want more time from iOS to complete a task, you have to tell iOS when you can finish that task, then your program will iOS 5 programming Cookbook www.devdiv.com Translation finishing

DevDiv translation: Kyelup cloudhsu patience Mocha wangli2003j3 Xiebaochun dymx101 jimmylianf beyondvincent devdiv proofreading: LAIGB kyelup DevDiv Series: Beyondvincent Version 1.0 | July 30, 2012

And all of its suspended threads are put into the background.

When your program is in the foreground, the UIApplication backgroundtimeremaining property equals the Dbl_max constant, which is the maximum value that the double type can represent (and the equivalent of this value is usually equal to-1). When iOS is required to give more execution time before the program is fully suspended, this property indicates how many seconds the program has before completing the task.

In the program you can call Beginbackgroundtaskwithexpirationhandler multiple times: method. The important point to remember is that when iOS returns a token or task identifier (task identifier) for your program, you must call Endbackgroundtask: Method, which is used to flag the end of the task at the end of the running task. If you do not do this, iOS will terminate your program.

In the background, the program should not perform full functionality, nor should it handle large amounts of data. In fact, they should only complete a long-term task.

For example, a program is invoking a Web service API and has not received a response from that API on the server. During this period, if the program is sent back 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 state and call UIApplication's Endbackgroundtask: instance method to mark the task as complete.

Let's look at an example. I'll start with a property that defines a uibackgroundtaskidentifier type in the application delegate. At the same time, let's define a nstimer, and when the program is sent to the background, we'll use it to output a message to the console window every 1 seconds:

#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) Nstimer *mytimer;

@end

Next we continue to synchronize the properties:

#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 the 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 Finishing

DevDiv translation: Kyelup cloudhsu patience Mocha wangli2003j3 Xiebaochun dymx101 jimmylianf beyondvincent devdiv proofreading: LAIGB kyelup DevDiv Series: Beyondvincent Version 1.0 | July 30, 2012

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];

}]; }

As you can see, in the background task's completion handler (completion handler), we call the Endbackgroundtask method of the application delegate. 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; }

}); }

At the end of a long mission, we need to do something to clean up:

1. End all threads and timers, whether they are created in the base timer or GCD.

2. Call UIApplication's Endbackgroundtask: method to end the background task.

3. Set the task ID to Uibackgroundtaskinvalid, which marks the end of our task.

Finally, when our app goes back to the foreground, if our background task is still in execution, we need to make sure we're killing it:

-(void) Applicationwillenterforeground: (uiapplication *) application{

if (self.backgroundtaskidentifier! = uibackgroundtaskinvalid) {

[Self endbackgroundtask]; }

}

In our case, whenever the program is sent to the background, we will ask for more time to complete a long-term task (for example, here is the code for our timers). In our time, we constantly read the value of the Backgroundtimeremaining property in the UIApplication instance and print it to the console. In UIApplication's Beginbackgroundtask Withexpirationhandler: Instance method, the code we provide will be executed before a long-term task is completed in the extra time of the program (one version is probably 5-10 seconds before the task expires). Here, we just call UIApplication's Endbackgroundtask: Instance method to end the task.

After the program is sent to the background, borrow time from IOS to complete long-term tasks-prepare

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.