【发布时间】:2014-01-16 11:52:33
【问题描述】:
我需要在我的应用程序运行时与服务器进行同步。 有时,这种同步可能需要几分钟。 在 iPhone 上,如果用户按下主页按钮或设备自动锁定,则此任务会中断。
我试过类似的东西:
backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
backgroundTaskID = UIBackgroundTaskInvalid;
}];
[self Synchronization];
funcao sincronizaçã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;
但是这段代码不起作用,有人知道我该如何克服这个挑战吗?
同步的方式是请求数据直到不再存在。但是使用此代码,它最终会出现在进入后台时正在接收的背景对象中
【问题讨论】:
标签: ios iphone multithreading background