我正在为推荐开发一款iPhone应用程序。它使用Parse来维护用户,联系人和推荐。它还使用Core Data与Parse同步并维护脱机活动。它有一个刷新方法,可以将Parse与Core Data同步。我试图找到一种方法,一旦用户离开应用程序,与Parse的同步在后台完成。我一直在applicationDidEnterBackground中使用简单的解析查询进行测试,但是无法正常工作。这是我使用的代码:
(void)applicationDidEnterBackground:(UIApplication *)application{
self.backgroundTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
[application endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *message = @"begin background task";
NSDictionary *dict = @{@"status": message};
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:kBeginBackgroundTaskWithNameKey];
PFQuery *query = [PFQuery queryWithClassName:@"Referral"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSString *message = [NSString stringWithFormat:@"array has %lu objects", (unsigned long)objects.count];
NSDictionary *dict = @{@"status": message};
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:kBeginBackgroundTaskWithNameKey];
[application endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}
}];
});
}
我做错了什么?
答案 0 :(得分:0)
我终于找到了解决问题的方法。我使用了Ray Wenderlich教程" iOS中的背景模式"作为指导http://www.raywenderlich.com/29948/backgrounding-for-ios。这里是AppDelegate的主要变化:
- (无效)parseSync {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Parse code ....
});
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Background handler called. Not running background tasks anymore.");
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}];
}
(void)applicationWillResignActive:(UIApplication *)application {
[self parseSync];
}