iOS后台进程
问题描述:
当我的应用程序正在运行时,我需要与服务器进行同步。 有时这种同步可能需要几分钟的时间。 在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;
但是这个代码不工作,任何人有一个想法我怎么能克服这个挑战?
同步的方式是询问数据直到不再存在。但是使用此代码,它只会在进入后台时收到的背景对象中结束
答
您的代码在过期处理程序中调用[self synchronization];
。该块仅在您的应用程序用完后台运行时才被调用。所以你只有在没有时间去做的时候才会开始同步。
拨打电话[self synchronization];
以外的区块。该块应包含清理/暂停代码,并结束后台任务...
另外,看看使用NSURLSession
为好的iOS 7兼容性。
现在只需下载当前包。我需要下载大约8次,并存储在需要5到10分钟的核心数据中。有什么建议么? – Pedro
你的意思是你需要下载8个响应,而不是1个。你可以同时运行4个下载(使用不同的线程)。你的主要问题是你不能确定你将被授予多少背景时间(url会话有帮助)。 – Wain
我看到你正在使用RestKit,它还不支持URL会话。您可以查看设置对象管理器操作队列的并发操作计数并同时创建所有需要的下载。 – Wain