iOS 应用程序在后台执行任务 [英] iOS application executing tasks in background
问题描述
我想知道是否可以在我的应用程序在后台时发送一些网络服务调用.Skype 是如何做到的?即使我按下主页按钮,我的电话也会保持连接.
I was wondering if I could send some webservice calls while my application is in the background. How does skype do it? Even if I press the home button my call stays connected.
推荐答案
根据 rckoenes 所述,允许应用程序注册要在用户点击主页按钮后完成的后台任务.完成这些任务有 10 或 15 分钟的时间限制.同样,您可以在用户回家后立即注册要完成的任务,这不允许您在他们退出应用后一小时执行代码.
Building on what rckoenes stated, applications are allowed to register background tasks to be completed after the user hits the home button. There is a time limit of 10 or 15 minutes for these tasks to complete. Again, you can register a task to complete immediately after the user hits home, this does NOT allow you to execute code say an hour after they exit the app.
UIApplication* app = [UIApplication sharedApplication];
task = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:task];
task = 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.
NSLog(@"Started background task timeremaining = %f", [app backgroundTimeRemaining]);
if (connectedToNetwork) {
// do work son...
}
[app endBackgroundTask:task];
task = UIBackgroundTaskInvalid;
});
更新:如果您的应用支持 iOs 4 之前的 iOS 版本,您还应该检查以确保在注册后台任务之前支持多任务处理.使用以下内容:
UPDATE: if your app supports versions of iOS previous to iOs 4, you should also check to ensure that multitasking is supported before registering a background task. Use something along the lines of:
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
backgroundSupported = device.multitaskingSupported;
这篇关于iOS 应用程序在后台执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!