iOS后台进程

时间:2014-01-16 11:52:33

标签: ios iphone multithreading background

我的应用程序运行时需要与服务器进行同步。 有时这种同步可能需要几分钟。 在iPhone上,如果用户按下主页按钮或设备自动锁定,则此任务会中断。

我尝试过类似的事情:

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;

但是这段代码不起作用,任何人都知道如何克服这一挑战?

同步的方法是在不再存在之前询问数据。但是使用此代码,它最终会出现在进入后台的时候接收的背景对象

1 个答案:

答案 0 :(得分:3)

您的代码在到期处理程序中调用[self synchronization];。仅当您的应用程序在后台运行时间不足时才会调用该块。因此,您只是在没有时间进行同步时尝试启动同步。

在区块外呼叫[self synchronization];。该块应包含清理/暂停代码并结束后台任务...

另外,请使用NSURLSession来获得良好的iOS 7兼容性。