问题描述
我对如何以及何时使用beginBackgroundTaskWithExpirationHandler
感到困惑.
I'm a bit confused about how and when to use beginBackgroundTaskWithExpirationHandler
.
Apple在示例中显示了在applicationDidEnterBackground
委托中使用它的时间,以便有更多的时间完成一些重要的任务,通常是网络事务.
Apple shows in their examples to use it in applicationDidEnterBackground
delegate, to get more time to complete some important task, usually a network transaction.
在查看我的应用程序时,似乎我的大多数网络内容都很重要,并且当我启动某个应用程序时,如果用户按下主屏幕按钮,我想完成它.
When looking on my app, it seems like most of my network stuff is important, and when one is started I would like to complete it if the user pressed the home button.
那么为了安全起见,用beginBackgroundTaskWithExpirationHandler
包装每个网络事务(并且我不是在谈论下载大块数据,主要是一些短xml)是否被接受/是一种好习惯?
So is it accepted/good practice to wrap every network transaction (and I'm not talking about downloading big chunk of data, it mostly some short xml) with beginBackgroundTaskWithExpirationHandler
to be on the safe side?
推荐答案
如果您希望网络事务在后台继续进行,则需要将其包装在后台任务中.完成操作后致电endBackgroundTask
也是非常重要的-否则该应用将在分配的时间到期后被终止.
If you want your network transaction to continue in the background, then you'll need to wrap it in a background task. It's also very important that you call endBackgroundTask
when you're finished - otherwise the app will be killed after its allotted time has expired.
矿井看起来像这样:
- (void) doUpdate
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self beginBackgroundUpdateTask];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
// Do something with the result
[self endBackgroundUpdateTask];
});
}
- (void) beginBackgroundUpdateTask
{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void) endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
每个后台任务都有一个UIBackgroundTaskIdentifier
属性
I have a UIBackgroundTaskIdentifier
property for each background task
Swift中的等效代码
Equivalent code in Swift
func doUpdate () {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let taskID = beginBackgroundUpdateTask()
var response: URLResponse?, error: NSError?, request: NSURLRequest?
let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// Do something with the result
endBackgroundUpdateTask(taskID)
})
}
func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier {
return UIApplication.shared.beginBackgroundTask(expirationHandler: ({}))
}
func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) {
UIApplication.shared.endBackgroundTask(taskID)
}
这篇关于正确使用beginBackgroundTaskWithExpirationHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!