GCD之后台程序运行

  1. 云栖社区>
  2. 博客列表>
  3. 正文

GCD之后台程序运行

社会主义 2016-04-19 17:26:01 浏览481 评论0

摘要: 点击Home键进入后台时进行计时,直到从新启动,超过三分钟启动手势 // // AppDelegate.m // GCDDown // // Created by City--Online on 15/4/21.

点击Home键进入后台时进行计时,直到从新启动,超过三分钟启动手势


//
//  AppDelegate.m
//  GCDDown
//
//  Created by City--Online on 15/4/21.
//  Copyright (c) 2015年 CYW. All rights reserved.
//
 
#import "AppDelegate.h"
 
@interface AppDelegate ()
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
@property(nonatomic,assign)NSInteger count;
@property(nonatomic,strong)NSTimer *timer;
 
@end
 
@implementation AppDelegate
 
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    return YES;
}
 
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user 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 use this method to pause the game.
}
 
- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"进入后台");
    [self beingBackgroundUpdateTask];
    // 在这里加上你需要长久运行的代码
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updatecount) userInfo:nil repeats:YES];
    [self.timer fire];
    [self endBackgroundUpdateTask];
}
-(void)updatecount
{
    self.count++;
}
- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}
 
- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"进入前台");
    NSLog(@"%ld",self.count);
    self.count=0;
    [self.timer invalidate];
     
}
 
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
 
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
 
@end




用云栖社区APP,舒服~

【云栖快讯】云栖社区技术交流群汇总,阿里巴巴技术专家及云栖社区专家等你加入互动,老铁,了解一下?  详情请点击

网友评论