iOS 7 SDK: 如何使用後臺獲取(Background Fetch)

本文主要教你如何使用iOS 7 SDK多任務處理API--Background Fetch。咱們生活在一個社交化的世界中,大部分用戶都安裝了幾個社交類app,可是每次用戶打開app,他們必需要等待app加載更新才能看到跟更多最新的內容,對於愈來愈沒耐心的用戶來講這一點無疑使人很是痛苦。如今,iOS 7的後臺獲取(Background Fetch)能夠很好地解決這個問題,在用戶打開應用以前,app就能自動更新獲取內容。 ios

 
以檢測流量的app爲例來講明Background Fetch如何工做。若是你會在天天早上查看應用,咱們假設在8:20 AM,,你的iOS app必須在當時得到信息。如今若是操做系統知道你將會在8:20 AM左右使用app,那麼它能夠提早得到數據,從而提供更好的用戶體驗。
 
關於iOS 7多任務執行更全面的概覽可參看咱們的主題「 iOS 7 SDK: Multitasking Enhancements」。如下咱們將會以一個實例工程來演示如何使用後臺獲取(Background Fetch)。
 
1.項目安裝

第一步是建立一個iOS 7項目,並選擇單視圖app,接着添加一些有用的屬性: 數組

@property (nonatomic) NSMutableArray *objects; 
@property (nonatomic) NSArray *possibleTableData; 
@property (nonatomic) int numberOfnewPosts; 
@property (nonatomic) UIRefreshControl *refreshControl;



NSMutablearray對象將會被用來在TableView中保存對象列表。在這個教程中,你將不能調用任何服務來得到數據。相反,你將使用possibleTableData數組,並隨機從中選擇幾個對象。整個numberOfnewPosts表明新發布的內容--每次進行請求或者接收後臺獲取時可用。refrestControl是一個在更新任務時使用的控件。因爲不在教程以內,因此本文不會在此展開。
 

在Main.storyboard中,把ViewController改成UITableViewController,下一步,點擊UITableViewController,轉到Editor > Embed in > Navigation Controller。記得把自定義類設置爲ViewController。而後轉至ViewController.m,第一步加載一些數據。如下代碼將會申請內存並建立數據對象,建立一個標題以及初始化refreshControl: app

self.possibleTableData = [NSArray arrayWithObjects:@"Spicy garlic Lime Chicken",@"Apple Crisp II",@"Eggplant Parmesan II",@"Pumpkin Ginger Cupcakes",@"Easy Lasagna", @"Puttanesca", @"Alfredo Sauce", nil]; 
self.navigationItem.title = @"Delicious Dishes"; 
self.refreshControl = [[UIRefreshControl alloc] init]; 
[self.refreshControl addTarget:self action:@selector(insertNewObject:) forControlEvents:UIControlEventValueChanged]; 
[self.tableView addSubview:self.refreshControl];

以上代碼將會產生一個提醒,由於咱們丟失了insertNewObject method。讓咱們來解決它。該方法將會產生一個隨機數,而且將從日期數組得到對象相同的數據,而後它將會經過新值來更新tableview。 dom

- (void)insertNewObject:(id)sender 
{ 
    self.numberOfnewPosts = [self getRandomNumberBetween:0 to:4]; 
    NSLog(@"%d new fetched objects",self.numberOfnewPosts); 
    for(int i = 0; i < self.numberOfnewPosts; i++){ 
        int addPost = [self getRandomNumberBetween:0 to:(int)([self.possibleTableData count]-1)]; 
        [self insertObject:[self.possibleTableData objectAtIndex:addPost]]; 
    } 
    [self.refreshControl endRefreshing]; 
}

當你添加如下方法時,getRandomNumberBetween提醒將會被禁止: iphone

-(int)getRandomNumberBetween:(int)from to:(int)to { 
    return (int)from + arc4random() % (to-from+1); 
}



爲了在 NSArray object上加載對象,咱們須要執行TableView委託函數。 函數

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return self.objects.count; 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
    cell.textLabel.text = self.objects[indexPath.row]; 
    if(indexPath.row < self.numberOfnewPosts){ 
        cell.backgroundColor = [UIColor yellowColor]; 
    } 
    else 
        cell.backgroundColor = [UIColor whiteColor]; 
    return cell; 
}

很是簡單吧?若是運行項目,你會看到一個相似下圖的界面:
2. Background Fetch
如今開始建立Background Fetch功能,首先從Project開始,接着是Capabilities,而後Put Background Modes ON,再選擇Background Fetch,以下圖所示:

但僅僅作這個是不夠的。默認地,app不會調用後臺API,因此你須要在AppDelegate.m文件中把如下代碼添加至-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method. 測試

[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

這個可讓系統決定什麼時候應該展現新內容。如今你的app已經知道啓動ackground fetch,讓咱們告訴它要作些什麼。方法-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler將會對你有所幫助。每當執行後臺獲取時該方法都會被調用,而且應該被包含在AppDelegate.m文件中。如下是完整版本:
   
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { 
    UINavigationController *navigationController = (UINavigationController*)self.window.rootViewController; 
    id topViewController = navigationController.topViewController; 
    if ([topViewController isKindOfClass:[ViewController class]]) { 
        [(ViewController*)topViewController insertNewObjectForFetchWithCompletionHandler:completionHandler]; 
    } else { 
        NSLog(@"Not the right class %@.", [topViewController class]); 
        completionHandler(UIBackgroundFetchResultFailed); 
    } 
}



下一步你應該也把ViewController頭文件放進AppDelegate.m類。
#import "ViewController.h" 
注意insertNewObjectForFetchWithCompletionHandler並無被建立,因此還須要在ViewController.h中聲明它。
 
- (void)insertNewObjectForFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;  

如今關注執行文件,相似於以前insertNewObject調用的添加。咱們使用completionHandler來和系統「交流」,並讓它告訴咱們app是否如今獲取數據,或者當前是否有有效數據。 fetch

- (void)insertNewObjectForFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { 
    NSLog(@"Update the tableview."); 
    self.numberOfnewPosts = [self getRandomNumberBetween:0 to:4]; 
    NSLog(@"%d new fetched objects",self.numberOfnewPosts); 
    for(int i = 0; i < self.numberOfnewPosts; i++){ 
        int addPost = [self getRandomNumberBetween:0 to:(int)([self.possibleTableData count]-1)]; 
        [self insertObject:[self.possibleTableData objectAtIndex:addPost]]; 
    } 
    /* 
     At the end of the fetch, invoke the completion handler. 
     */ 
    completionHandler(UIBackgroundFetchResultNewData); 
}

完成代碼,如今咱們模擬一個測試,並驗證全部項目都能啓動和運行。
 
3. Simulated Background Fetch
若是想肯定是否每件事都已經配置好了,你須要編輯Schemes,在Schemes列表點擊Manage Schemes選項,以下:
 
在Schemes管理區你能夠複製app的scheme:
 
複製後scheme會在新窗口展現。你可在Options標籤下更改它的名稱。選擇「Launch due to a background fetch event」框,並在全部窗口中點擊「OK」。
 
接着,使用複製的scheme運行app。注意app不會在前臺打開,可是它應該已經得到了一些內容。若是打開app,而且幾個recipe已生效,那就說明操做已經成功了。爲了使用後臺獲取功能,你也能夠從Xcode菜單的Debug > Simulate Background Fetch開始。
 
源文件下載:
/cms/uploads/soft/131113/4673-131113193430.zip
 
來源: mobile.tutsplus
相關文章
相關標籤/搜索