【发布时间】:2014-02-18 16:37:26
【问题描述】:
我是 ios7 后台获取的新手。这是我的做法。
这就是appDelegate中发生的事情:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *url = [[NSURL alloc] initWithString:@"http://sample.com/api/home/lastnews"];
OldJson = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
}
请注意,这里我将整个 JSON 文件存储在一个字符串中,以便我可以使用它来检查新内容。
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
//HomepageView is the view controller that is supposed to be updated
HomepageView *homepage = [[HomepageView alloc] init];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURL *url = [[NSURL alloc] initWithString:@"http://sample.com/api/home/lastnews"];
NewJson = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURLSessionDataTask *task = [session dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
completionHandler(UIBackgroundFetchResultFailed);
return;
}
if (![NewJson isEqualToString:OldJson])
{
completionHandler(UIBackgroundFetchResultNewData);
NSLog(@"New Data : %@",NewJson);
}
else
{
completionHandler(UIBackgroundFetchResultNoData);
NSLog(@"Old Json : %@",OldJson);
}
}];
// Start the task
[task resume];
}
现在要测试整个过程,我只需运行应用程序。然后我将它发送到后台,然后当我在 JSON 文件中有新内容时,我使用 Debug 菜单中的 Simulate Background Fetch 操作。然后我打开应用程序,但没有任何改变。
【问题讨论】:
-
您在完成处理程序中得到了什么?
-
一件事:只有主线程才能修改UI。
-
@CW0007007 你是什么意思?
-
@Larme 好的,这是否意味着我无法更新 appdelegate 中的 UI?那么后台抓取有什么意义呢?
-
您可以通过后台获取数据并通知主线程上的处理程序需要更新。有几种方法可以做到,我喜欢用 NSNotificationCenter:developer.apple.com/library/ios/documentation/Cocoa/Reference/…
标签: objective-c ios7 appdelegate