成人午夜激情影院,小视频免费在线观看,国产精品夜夜嗨,欧美日韩精品一区二区在线播放

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

2013-12-16 10:32:22來源:看引擎作者:

本文主要教你如何使用iOS 7 SDK多任務處理API–Background Fetch。我們生活在一個社交化的世界中,大部分用戶都安裝了幾個社交類app,但是每次用戶打開app,他們必須要等待app加載更新才能看到跟更多最新的內容

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

以檢測流量的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:

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。

- (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提醒將會被禁止:

-(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是否現在獲取數據,或者當前是否有有效數據。

- (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開始。

關鍵詞:iOS
主站蜘蛛池模板: 高尔夫| 保山市| 中阳县| 石渠县| 渭源县| 嘉鱼县| 喜德县| 夏津县| 呼和浩特市| 三原县| 惠州市| 和田县| 万载县| 濮阳市| 龙岩市| 乌鲁木齐市| 大庆市| 子长县| 陵川县| 育儿| 来宾市| 恭城| 长泰县| 贵州省| 东明县| 凤山县| 铜川市| 革吉县| 徐水县| 美姑县| 三台县| 石屏县| 日喀则市| 恩平市| 常宁市| 广丰县| 迁西县| 马鞍山市| 杭锦旗| 泸州市| 台南市|