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

这篇文章是针对斯坦福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];
    ...
}
测试一下!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值