当应用程序进入后台时,是否可以调用webRequest?

时间:2013-03-07 09:14:54

标签: iphone ios ios5 ios6

我想在按下主页按钮并且应用程序进入后台时上传图像。 可能吗?如果是,那怎么样?如果没有那么我还有其他选择吗? 提前谢谢......

2 个答案:

答案 0 :(得分:3)

您可以在特定时间使用此代码在后台执行任务 -

 UIBackgroundTaskIdentifier bgTask = 0;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask]; 
    }];
    self.silenceTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self
                                                       selector:@selector(startLocationServices) userInfo:nil repeats:YES];

参考: http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

我认为这会对你有所帮助。 :)

答案 1 :(得分:1)

应用可以请求在关闭后最多10分钟内在后台运行,以便它可以完成长时间运行的任务。只允许某些进程在后台运行。请参阅实施长时间运行的后台任务部分in this reference.

如果你的应用是允许的,你可以尝试下面的代码:

- (void)applicationDidEnterBackground:(UIApplication *)application

{

    UIBackgroundTaskIdentifier bgTask;
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

        // Clean up any unfinished task business by marking where you

        // stopped or ending the task outright.

        [application endBackgroundTask:bgTask];

        bgTask = UIBackgroundTaskInvalid;

    }];



    // Start the long-running task and return immediately.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{



        // Do the work associated with the task, preferably in chunks.



        [application endBackgroundTask:bgTask];

        bgTask = UIBackgroundTaskInvalid;

    });

}

如果你想知道你的应用还剩多少时间来运行

NSTimeInterval ti = [[UIApplication sharedApplication]backgroundTimeRemaining];
NSLog(@"Remaining Time: %f", ti); // just for debug

如需更多参考,请使用此reference PDF(page 60)