3
4

2 回答 2

2

So what is the advantage of using begin​Background​Task​With​Expiration​Handler ?

If you are going to use URLSessionConfiguration.background, there is no such advantage and you should not use beginBackgroundTask(expirationHandler:) at all. Your entire premise (your very first sentence) was wrong. Uploading a file is not a good use case for beginBackgroundTask(expirationHandler:). It's a good use case for URLSessionConfiguration.background. The two things have nothing to do with each other.

于 2017-03-31T20:44:20.947 回答
2

This background task will let your app continue to run in background after the user leaves your app for an extra 3 minutes or so (check background​Time​Remaining for actual value) to let your request finish. And, yes, near the end of that 3 minutes, the timeout handler will be called if you haven't yet ended the background task.

So, if you end the background task during the normal flow of your app, this timeout closure won't need to be called. This closure is solely for any quick, last minute cleanup, that you might need to do before your app stops running in the background because it timed out before you had a chance to indicate that the background task ended. It's not for starting anything new, but just any last second clean-up. And make sure to end the background task in this timeout handler ... if you don't end the background task, the OS will summarily kill your app rather than just suspending it. Often, the only thing you need to do in this timeout closure is end the background task, but if you need to do any other cleanup, this is where you can do it.

Needless to say, you must end your background task (either when the network request finishes, or in the timeout handler if your app didn't yet get a chance to end the background task in its normal flow). If you don't, your app won't just be suspended, but rather it will be killed.

Regarding making assumptions about what happens when your app is restarted by the user later, you can't make any assumes about which app delegate method will be called. Even if you gracefully ended the background task, you have no assurances that it won't get jettisoned for other reasons (e.g. memory pressure). So don't assume anything.

于 2017-03-31T21:50:04.993 回答