斯坦福iOS7 2013-2014秋Assignment 6的一种答案 #3

来源:互联网 发布:淘宝网秋装新款 编辑:程序博客网 时间:2024/06/03 14:02

这篇文章是针对斯坦福iOS7 2013-1014的公开课Assignment 6 Top Regions所进行的解答的第三部分。

7.Fetch the URLforRecentGeoreferencedPhotos from Flickr periodically (a few times an hour when your application is in the foreground and whenever the system will allow when it is in the background using the background fetching API in iOS). You must load this data into a Core Data database with whatever schema you feel you need to do the rest of this assignment.

本节接着实现#2未完成的要求。

首先使用白胡子老师课上介绍的NSTimer来实现periodically fetch

- (void)startFlickrFetch:(NSTimer *)timer{    [self startFlickrFetch];}#define FOREGROUND_FLICKR_FETCH_INTERVAL (15 * 60) - (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    [self startFlickrFetch];    [NSTimer scheduledTimerWithTimeInterval:FOREGROUND_FLICKR_FETCH_INTERVAL                                     target:self                                   selector:@selector(startFlickrFetch:)                                   userInfo:nil                                    repeats:YES];       return YES;}

接着实现后台获取,也很简单,只需要使用一个appDelegate 方法,然后把completion handler传递给#2中的“handleEventsForBackgroundURLSession” appDelegate 方法就可以自动实现了。

- (void)application:(UIApplication *)applicationperformFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{    [FlickrHelper loadRecentPhotosOnCompletion:^(NSArray *photos, NSError *error) {        if (error) {            NSLog(@"Flickr background fetch failed: %@", error.localizedDescription);            completionHandler(UIBackgroundFetchResultFailed);        } else {            NSLog(@"%d photos fetched", [photos count]);            completionHandler(UIBackgroundFetchResultNewData);        }    }];}

然而,由于我们希望成为“good background citizens”,我们要在FlickrHelper中禁用蜂窝数据网络,并限制超时的时限,在config和session之间加入下面的代码。

#define BACKGROUND_FLICKR_FETCH_TIMEOUT 10+ (void)loadRecentPhotosOnCompletion:(void (^)(NSArray *places, NSError *error))completionHandler{    ...    config.allowsCellularAccess = NO;    config.timeoutIntervalForRequest = BACKGROUND_FLICKR_FETCH_TIMEOUT;    ...}

但是我们希望让app尽可能经常地调用后台来fetch(不然有可能iOS设备可能永远不会调用。。。),在NSTimer之前接入下面的代码

- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    ...    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];    ...}
测试一下!

0 0