AlamoFire Download in Background Session
Asked Answered
G

3

45

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 to override SessionDelegate to get it works? Or just backgroundCompletionHandler?

Typically what are the steps to handle downloads in background using Alamofire? And how can I handle the case where my app is relauch, with downloads in flux.

Godden answered 9/5, 2015 at 0:21 Comment(1)
github.com/Alamofire/Alamofire, go to section Downloading a File, and Alamofire requests are asynchronousDevastating
H
34

Update

Based on this amazing tutorial, I have put together an example project available on GitHub. It has an example for background session management.

According to Apple's URL Loading System Programming Guide:

In both iOS and OS X, when the user relaunches your app, your app should immediately create background configuration objects with the same identifiers as any sessions that had outstanding tasks when your app was last running, then create a session for each of those configuration objects. These new sessions are similarly automatically reassociated with ongoing background activity.

So apparently by using the appropriate background session configuration instances, your downloads will never be "in flux".

I have also found this answer really helpful.

Original answer

From Alamofire's GitHub page:

Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (HTTPAdditionalHeaders) or timeout interval (timeoutIntervalForRequest).

By default, top level methods use a shared Manager instance with default session configuration. You can however create a manager with background session configuration like so:

let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background")
let manager = Alamofire.Manager(configuration: configuration)

You can then make requests using this Manager instance.

manager.startRequestsImmediately = true
let request = NSURLRequest(URL: NSURL(string: "your.url.here")!)
manager.request(request)

By looking at its implementation, it also has a property called backgroundCompletionHandler, so you can add a completion block:

manager.backgroundCompletionHandler = {
        // do something when the request has finished
    }
Hessney answered 15/5, 2015 at 22:25 Comment(1)
My destinationURL is nil if I fire a download request with the above URL. and the file downloaded doesnt get downloaded using above manager. @JózsefVeszaRollmop
D
33

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
    }
}
Dialogist answered 20/10, 2015 at 15:54 Comment(1)
This won't work, see github.com/Alamofire/Alamofire/commit/…Arp
C
10

I was searching for the solution quite long. Until read the article mentioned above. The issue for me was - I had to enable External accessory communication

enter image description here

Everything else was done as described above. AppDelegate:

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        BackendAPIManager.sharedInstance.backgroundCompletionHandler = completionHandler
    }

Singleton:

import Alamofire

class BackendAPIManager: NSObject {
    static let sharedInstance = BackendAPIManager()

    var alamoFireManager : Alamofire.SessionManager!

    var backgroundCompletionHandler: (() -> Void)? {
        get {
            return alamoFireManager?.backgroundCompletionHandler
        }
        set {
            alamoFireManager?.backgroundCompletionHandler = newValue
        }
    }

    fileprivate override init()
    {
        let configuration = URLSessionConfiguration.background(withIdentifier: "com.url.background")
        configuration.timeoutIntervalForRequest = 200 // seconds
        configuration.timeoutIntervalForResource = 200
        self.alamoFireManager = Alamofire.SessionManager(configuration: configuration)
    }
}

And the calls are done in the following way:

BackendAPIManager.sharedInstance.alamoFireManager.upload(multipartFormData: { (multipartFormData) in ...
Conceptionconceptual answered 8/2, 2017 at 13:59 Comment(3)
Does your app not need to actually have functionality whereby it communicate with an external accessory in order for Apple to approve an app with this background mode ticked?Vertebra
Why do you need to enable External accessory communication? This becomes an issue when submitting the app to the AppStore.Uniliteral
It's a really poor solution when you tell people to tick "magic boxes" without explaining why, or how it affects App Store acceptance.Decennium

© 2022 - 2024 — McMap. All rights reserved.