"Code Notes" run in the background, you can choose between the foreground or the background or the front and back

Source: Internet
Author: User

One, engineering drawings.

Two, code.

AppDelegate.h

Appdelegate.m

RootViewController.h

#import <UIKit/UIKit.h> @interface appdelegate:uiresponder <UIApplicationDelegate> @property (Strong, nonatomic) UIWindow *window; @property (nonatomic, unsafe_unretained) uibackgroundtaskidentifier Backgroundtaskidentifier, @property (nonatomic, strong) Nstimer *mytimer; @end

Rootviewcontroller.m

#import "AppDelegate.h" #import "RootViewController.h" @implementation appdelegate-(BOOL) application: (uiapplication *) Application Didfinishlaunchingwithoptions: (nsdictionary *) launchoptions{Self.window = [[UIWindow alloc]    Initwithframe:[[uiscreen Mainscreen] bounds];        Override point for customization after application launch.    Rootviewcontroller *rootvc=[[rootviewcontroller Alloc]init];    Uinavigationcontroller *nav=[[uinavigationcontroller ALLOC]INITWITHROOTVIEWCONTROLLER:ROOTVC];            Self.window.rootviewcontroller=nav;    Self.window.backgroundColor = [Uicolor Whitecolor];    [Self.window makekeyandvisible]; return YES;} -(void) Applicationwillresignactive: (uiapplication *) application{//Sent when the application was about to move from AC tive to inactive state. This can occur for certain types of temporary interruptions (such as a incoming phone call or SMS message) or when the US Er quits the application and it begins the transition to the background statE.//Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should with this method to pause the game.} -(void) Applicationdidenterbackground: (uiapplication *) application{//Use this method to free up public resources, store user data, stop our defined timers (timers)    , and stores information about the program before it 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.    Marking a long-running background task will start//through debugging, found that iOS gave us an additional 10 minutes (600s) to perform this task. Self.backgroundtaskidentifier =[application beginbackgroundtaskwithexpirationhandler:^ (void) {//When the application is left behind        When the time is near the end (the application leaves a limited amount of time to execute in the background), the block blocks will be executed//We need to perform some cleanup work in the sub block blocks.    If the cleanup fails, it will cause the program to hang//clean up the work in a synchronous way in the main thread [self endbackgroundtask];        }];                                                   Simulates a long-running Task self.mytimer =[nstimer scheduledtimerwithtimeinterval:1.0f Target:self selector: @selector (timermethod:) useriNfo:nil Repeats:yes];    }-(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//per pair Beginbackgroundt Askwithexpirationhandler: Method Invocation, you must call Endbackgroundtask: Method 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 completion [[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskIdentifier];        Destroy background task identifier strongself.backgroundtaskidentifier = Uibackgroundtaskinvalid; }    });}    A long-running Task method for impersonation-(void) Timermethod: (Nstimer *) paramsender{//backgroundtimeremaining attribute contains the time that the program left for us Nstimeinterval backgroundtimeremaining =[[uiaPplication sharedapplication] backgroundtimeremaining];    if (backgroundtimeremaining = = Dbl_max) {//foreground print NSLog (@ "Background time Remaining = undetermined");    } else {//spool NSLog (@ "Background time Remaining =%.02f Seconds", backgroundtimeremaining); }}-(void) Applicationwillenterforeground: (uiapplication *) application{//called as part of the transition from the BAC Kground to the inactive state;        Here's can undo many of the changes made on entering the background. Add this code, it will not run in the foreground. Otherwise, the front and rear stations will run together.        In addition to the first boot, the foreground is not running, exiting the background when running.    if (self.backgroundtaskidentifier! = uibackgroundtaskinvalid) {[Self endbackgroundtask]; }}-(void) applicationdidbecomeactive: (uiapplication *) application{//Restart Any tasks this were paused (or not yet St arted) While the application was inactive. If the application is previously in the background, optionally refresh the user interface.} -(void) Applicationwillterminate: (uiapplication *) application{//Called when the application was about to terminate. Save data if appropriate. See also Applicationdidenterbackground:.} @end

  

"Code Notes" run in the background, you can choose between the foreground or the background or the front and back

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.