2014-11-04 49 views
0

我正在開發一個推薦的iphone應用程序。它使用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

我終於找到了解決我的問題的方法。我使用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; 
}]; 

}

  • (無效)applicationWillResignActive:(UIApplication的*)應用{

    [自parseSync ]。

}