I am using Alamofire within a new app (A Download Manager Sample based on Alamofire) I need some clarifications about downloading files using the background session. I need
EDIT
With Alamofire 5 this is no longer possible, see the release notes:
Using a
URLSessionConfiguration
with a background identifier is not possible any more. We're explicitly ensuring Alamofire isn't used with background sessions, in order to prevent ongoing issues around support and surprise on the part of the user.
Old answer, still valid if you use Alamofire 4
It's actually very easy with Alamofire:
1) your Alamofire.Manager should be configured with a background session identifier:
class NetworkManager {
...
private lazy var backgroundManager: Alamofire.SessionManager = {
let bundleIdentifier = ...
return Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: bundleIdentifier + ".background"))
}()
...
}
2) in the App Delegate implement application(_:handleEventsForBackgroundURLSession:completionHandler:
and pass the completion handler to Alamofire.SessionManager.backgroundCompletionHandler
.
In my case the app delegate method looks like
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
NetworkManager.default.backgroundCompletionHandler = completionHandler
}
and my network manager has a computed property like this to set the Manager property:
var backgroundCompletionHandler: (() -> Void)? {
get {
return backgroundManager.backgroundCompletionHandler
}
set {
backgroundManager.backgroundCompletionHandler = newValue
}
}