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

本文深入探讨了如何利用NSTimer实现iOS7 Stanford公开课Assignment6TopRegions中关于Flickr数据的周期性后台抓取,以及如何将获取的数据整合到Core Data数据库中。重点介绍了前台与后台数据抓取的实现方法,以及在FlickrHelper中设置网络请求限制和确保应用成为“好背景公民”的技巧。此外,还讨论了如何调整最小背景刷新间隔以保持数据更新频率。

这篇文章是针对斯坦福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 *)application
didFinishLaunchingWithOptions:(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 *)application
performFetchWithCompletionHandler:(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 *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ...
    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    ...
}
测试一下!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值