iOS7 Background Fetch 的實現過程

來源:互聯網
上載者:User

標籤:des   style   blog   class   code   c   

iOS7中加入了後台擷取(Background Fetch)的特性,這個特性使得使用者在開啟應用之前應用就可以執行部分代碼,比如準備資料,重新整理UI等等。這個時常一般最大是30秒。

以下是設定Background Fetch的基本步驟,記錄一下。

 

1. 點擊Target下的Capabilities ->>Background Modes ->>Background fetch 打鉤。

 

2. 設定fetch最短間隔

可以直接在AppDelegate裡面的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法內加上

[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

UIApplicationBackgroundFetchIntervalMinimum 是告訴系統儘可能頻繁的進行Background fetch,但是這個頻率多頻繁呢?這個是系統自己決定的,開發人員就無法得知啦。

即使你把 MinimumBackgroundFetchInterval 設的很小,系統也只能保證在這個時間段內程式不會被喚醒,而不是說每過這麼長時間就會被喚醒。因此,開發人員應該理性設定喚醒的時間,根據程式的具體情況來考慮。

 

3. 接下來就可以實現這個帶Block回調的 Background fetch 的代理方法了。

在這裡我們可以進行網路請求查看是否資料有更新。不過因為逾時限制是 30秒,所以若超過這個時間,就需要使用Background Transfer Service。

我在這個方法裡面寫了一個本地通知用來測試。

//-------------------------------------------------------------#pragma mark - Background fetch related delegate//-------------------------------------------------------------- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{    NSLog(@"我就是傳說中的Background Fetch??");    UILocalNotification * localNoti = [[UILocalNotification alloc] init];    localNoti.hasAction = YES;    //滑動來...    NSArray * actionMsgs = @[@"查看一個巨大的秘密",@"看看小夥伴在做什麼",@"看美女圖片",@"領取獎品",@"看看洪哥在做什麼",@"掏錢買下一個DropBeacon",@"請世文吃飯"];    localNoti.alertAction = [actionMsgs objectAtIndex:arc4random()%actionMsgs.count];    localNoti.alertBody = @"我就是傳說中的Background Fetch??";    [[UIApplication sharedApplication] scheduleLocalNotification:localNoti];    completionHandler(UIBackgroundFetchResultNewData);}

 

4. 接下來就可以進行測試了。

測試的方法有兩種。

第一種可以在RunScheme的選項中勾選Launch due to a background fetch event,如

 

第二種方式是選擇Xcode 功能表列的 Debug下的 Simulate Background Fetch來將模擬器直接切換到 Background Fetch狀態,如

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.