1
當我的應用程序正在運行時,我需要與服務器進行同步。 有時這種同步可能需要幾分鐘的時間。 在iPhone上,如果用戶按主頁按鈕或設備自動鎖定,則此任務會中斷。iOS後臺進程
我想是這樣的:
backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
backgroundTaskID = UIBackgroundTaskInvalid;
}];
[self Synchronization];
funcaosincronização:
-(void)Synchronization{
object=nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[TheAppDelegate setSync:YES];
send = NO;
responseObj = [[ConteinerInicial alloc] init];
object = [self fillObjectContainer:1];
error = NO;
[[objectManager HTTPClient] setDefaultHeader:@"Token" value:TheAppDelegate.token.token];
[[objectManager HTTPClient] setDefaultHeader:@"Username" value:TheAppDelegate.token.userName];
[[objectManager HTTPClient] setDefaultHeader:@"IDDevice" value:TheAppDelegate.token.IDDevice];
[objectManager postObject:object path:@"" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result){
NSArray *response = [result array];
NSLog(@"Loading mapping result: %@", result);
NSDictionary *headerDictionary = [operation.HTTPRequestOperation.response allHeaderFields];
NSString *authenticationStatus = [headerDictionary objectForKey:@"AuthenticationStatus"];
// if server returns "NotAuthorized", user must login again
if ([authenticationStatus isEqualToString:@"NotAuthorized"]) {
[AppDelegate showErrorAlert:@"Login expired!"];
[TheAppDelegate clearLoginToken];
error = YES;
return;
}
responseObj = [response objectAtIndex:0];
if(responseObj.Package.count>0)
{
[self savePackage:responseObj tipo:1];
[self Synchronization];
}else
{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
backgroundTaskID = UIBackgroundTaskInvalid;
}
} failure: ^(RKObjectRequestOperation *operation, NSError *reportError){
RKLogError(@"Operation failed with error: %@", reportError);
[AppDelegate showErrorAlert:@"There is some problem with the connection or the server! Please, check your connection or the address of the server and try again."];
send = YES;
[TheAppDelegate setSync:NO];
error = YES;
}];
});
}
而在同步結束準備:
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
backgroundTaskID = UIBackgroundTaskInvalid;
但是這個代碼不工作,任何人有一個想法我怎麼能克服這個挑戰?
同步的方式是詢問數據直到不再存在。但是使用此代碼,它只會在進入後臺時收到的背景對象中結束
現在只需下載當前包。我需要下載大約8次,並存儲在需要5到10分鐘的核心數據中。有什麼建議麼? – Pedro
你的意思是你需要下載8個響應,而不是1個。你可以同時運行4個下載(使用不同的線程)。你的主要問題是你不能確定你將被授予多少背景時間(url會話有幫助)。 – Wain
我看到你正在使用RestKit,它還不支持URL會話。您可以查看設置對象管理器操作隊列的併發操作計數並同時創建所有需要的下載。 – Wain