Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

ios - AlamoFire Download in Background Session

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...