IOS background processing and ios background processing
Common Use of iOS background processing
1. Delete resources when you enter the Background: The less resources the application occupies when it is suspended, the lower the risk of the application being terminated by iOS. By clearing resources that are easy to re-create from the memory, you can increase the chance that the application will reside in the memory, thus greatly accelerating the restart.
2. Save the status when entering the background: Save all information related to the operations performed by the user. In this way, the user can still restore the progress when they return next time.
3. delayed execution and request for more background time: if it takes a lot of time to enter the background, the application may be removed from the memory. If the application is performing File Transfer and cannot be completed, this will cause a lot of inconvenience. We can use applicationDidEnterBackground as a platform to tell the system that you have additional work to do, and then start a program block to really execute the work.
Example:
@property (strong, nonatomic) UILabel *label;@property (strong, nonatomic) UIImage *smiley;@property (strong, nonatomic) UIImageView *smileyView;@property (strong, nonatomic) UISegmentedControl *segmentedControl;
@implementation BIDViewController { BOOL animate;}
-(Void) viewDidLoad {[super viewDidLoad]; CGRect bounds = self. view. bounds; CGRect labelFrame = CGRectMake (bounds. origin. x, CGRectGetMidY (bounds)-50, bounds. size. width, 100); // The rotated Label self. label = [[UILabel alloc] initWithFrame: labelFrame]; self. label. font = [UIFont fontWithName: @ "Helvetica" size: 70]; self. label. text = @ "Bazinga! "; Self. label. textAlignment = NSTextAlignmentCenter; self. label. backgroundColor = [UIColor clearColor]; // smiling face CGRect smileyFrame = CGRectMake (CGRectGetMidX (bounds)-42, CGRectGetMidY (bounds)/2-35, 84, 84); self. smileyView = [[UIImageView alloc] initWithFrame: smileyFrame]; self. smileyView. contentMode = UIViewContentModeCenter; NSString * smileyPath = [[NSBundle mainBundle] pathForResource: @ "smiley" ofType: @ "png"]; self. smiley = [UIImage imageWithContentsOfFile: smileyPath]; self. smileyView. image = self. smiley; // The slot self. segmentedControl = [[UISegmentedControl alloc] initWithItems: [NSArray arrayWithObjects: @ "One", @ "Two", @ "Three", @ "Four", nil]; self. segmentedControl. frame = CGRectMake (bounds. origin. x + 20, 50, bounds. size. width-40, 30); [self. view addSubview: self. segmentedControl]; [self. view addSubview: self. smileyView]; [self. view addSubview: self. label]; NSNumber * indexNumber = [[NSUserDefaults standardUserDefaults] objectForKey: @ "selectedIndex"]; if (indexNumber) {NSInteger selectedIndex = [indexNumber intValue]; self. segmentedControl. selectedSegmentIndex = selectedIndex;} // notify NSNotificationCenter * center = [nsicationicationcenter defacenter center]; [center addObserver: self selector: @ selector (applicationWillResignActive) name: Your object: nil]; [center addObserver: self selector: @ selector (applicationDidBecomeActive) name: jsonobject: nil]; [center addObserver: self selector: @ selector (applicationDidEnterBackground) name: jsonobject: nil]; [center addObserver: self selector: @ selector (applicationWillEnterForeground) name: UIApplicationWillEnterForegroundNotification object: nil];}
// Label downward-(void) rotateLabelDown {[UIView animateWithDuration: 0.5 animations: ^ {self. label. transform = transform (M_PI);} completion: ^ (BOOL finished) {[self rotateLabelUp];} // Label rotation up-(void) rotateLabelUp {[UIView animateWithDuration: 0.5 animations: ^ {self. label. transform = CGAffineTransformMakeRotation (0);} completion: ^ (BOOL finished) {if (animate) {[self rotateLabelDown] ;}}];}
// Exit activity status-(void) applicationWillResignActive {NSLog (@ "VC: % @", NSStringFromSelector (_ cmd); animate = NO ;} // enter the activity status-(void) applicationDidBecomeActive {NSLog (@ "VC: % @", NSStringFromSelector (_ cmd); animate = YES; [self rotateLabelDown];}
// Run in the background-(void) applicationDidEnterBackground {NSLog (@ "VC: % @", NSStringFromSelector (_ cmd); // obtain the shared UIApplication instance first. UIApplication * app = [UIApplication sharedApplication]; // declares the taskId variable and modifies it with _ block. _ Block UIBackgroundTaskIdentifier taskId; // tells the system that it takes more time to complete a task and promises to tell it after the task is completed. If the system determines that we have been running for too long and decides to stop running, we can call the program block taskId = [app beginBackgroundTaskWithExpirationHandler: ^ {NSLog (@ "Background task ran out of time and was terminated. "); [app endBackgroundTask: taskId];}]; // if the value returned by the system is UIBackgroundTaskInvalid, the system does not provide us with any additional time. If (taskId = UIBackgroundTaskInvalid) {NSLog (@ "Failed to start background task! "); Return;} // dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {NSLog (@" Starting background task with % f seconds remaining ", app. backgroundTimeRemaining); self. smiley = nil; self. smileyView. image = nil; // the position where segmentedControl is stored NSInteger selectedIndex = self. segmentedControl. selectedSegmentIndex; [[NSUserDefaults standardUserDefaults] setInteger: selectedIndex forKey: @ "selectedIndex"]; // simulate a 25-second process [NSThread sleepForTimeInterval: 25]; NSLog (@ "Finishing background task with % f seconds remaining", app. backgroundTimeRemaining); // tells the system that [app endBackgroundTask: taskId] has been completed;});}
// Enter the foreground-(void) applicationWillEnterForeground {NSLog (@ "VC: % @", NSStringFromSelector (_ cmd); NSString * smileyPath = [[NSBundle mainBundle] pathForResource: @ "smiley" ofType: @ "png"]; self. smiley = [UIImage imageWithContentsOfFile: smileyPath]; self. smileyView. image = self. smiley ;}
Running effect: