IOS背景工作

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   使用   

http://onevcat.com/2013/08/ios7-background-multitask/

IOS提供了以下多中方式處理背景工作

1:beginBackgroundTaskWithExpirationHandler

2:特定任務的幕後處理

3:後台擷取

4:推送喚醒

5:後台傳輸

其中後面3種方式IOS7之後才支援

 

beginBackgroundTaskWithExpirationHandler

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    _count = 0;    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(function) userInfo:nil repeats:YES];    return YES;}-(void)function {    _count++;    NSLog(@"function:%d",_count);}

上面代碼開啟了一個定時器,每隔一秒輸出count的值,但當我們的應用退到前台後定時器停止運行,我們可以通過函數beginBackgroundTaskWithExpirationHandler向系統請求更多地時間運行我們的代碼,這個"更多的時間"經過測試大概在3分鐘左右

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    _count = 0;    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(function) userInfo:nil repeats:YES];    return YES;}-(void)function {    _count++;    NSLog(@"function:%d",_count);}- (void)applicationDidEnterBackground:(UIApplication *)application{    _identifier = [application beginBackgroundTaskWithExpirationHandler:^{        NSLog(@"ss");                [application endBackgroundTask:_identifier];        _identifier = UIBackgroundTaskInvalid;    }];}

 _identifier是整型變數,beginBackgroundTaskWithExpirationHandler設定了一個逾時回呼函數,當超過3分鐘後背景工作將被掛起同時執行逾時函數,我們應該在逾時函數中調用endBackgroundTask,下面代碼展示了beginBackgroundTaskWithExpirationHandler更一般的調用方式

- (void)beginBackgroundTask {    UIApplication *application = [UIApplication sharedApplication];    _identifier = [application beginBackgroundTaskWithExpirationHandler:^{        [self endBackgroundTask];    }];}- (void)endBackgroundTask {    UIApplication *application = [UIApplication sharedApplication];    [application endBackgroundTask:_identifier];    _identifier = UIBackgroundTaskInvalid;}- (void)applicationDidEnterBackground:(UIApplication *)application{    [self beginBackgroundTask];        //背景工作                [self endBackgroundTask];}

 

 

後台擷取 

後台擷取是IOS7新增內容,它的核心作用是設定一個間隔,然後每隔一段時間喚醒應用處理相應地任務,比如我們使用的社交軟體,可以每個一定時間擷取最新的資訊,這樣下次我們進入後就不需要等待重新整理,使用後台擷取的步驟如下:

1:添加應用對後台擷取的支援,可以在plist檔案中修改UIBackgroundMode一項,增加fetch,或者在應用資訊的capabilities->background modes中勾選background fetch

2:設定最小後台擷取時間間隔

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];    return YES;}

如果不設定的話預設為UIApplicationBackgroundFetchIntervalNever,表示不擷取,而且這個值代表"最小"後台擷取時間間隔,這裡所指定的時間間隔只是代表了“在上一次擷取或者關閉應用之後,在這一段時間內一定不會去做後台擷取”,IOS並不會為了每一個應用頻頻喚醒CPU,具體喚醒時間得看系統調度,設定為UIApplicationBackgroundFetchIntervalMinimum表示儘可能的對我們的應用進行後台喚醒,這樣設定的缺點是耗電。

3:實現application:performFetchWithCompletionHandler 

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/zanglitao/"]];    NSURLSession *session = [NSURLSession sharedSession];    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {        if (error) {            NSLog(@"%@",[error localizedDescription]);            completionHandler(UIBackgroundFetchResultFailed);        } else {            ////更新UI            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);            completionHandler(UIBackgroundFetchResultNewData);        }    }];        [task resume];}

與beginBackgroundTaskWithExpirationHandler相似,系統提供了回調completionHandler,用於通知系統任務執行完畢

 

推送喚醒

1:在UIBackgroundModes添加remote-notification

2:更改推送的payload:需要在payload中添加content-available,並設定為1

3:實現推送喚醒代碼

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

代碼實現與上一種方式一致,任務實現完需要調用回調方法通知系統

 

後台傳輸

IOS7中提供了NSURLSession替代NSURLConnection實現資料轉送,NSURLSession的用法之前博文有提

 

IOS背景工作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.