Search code examples
cocoaswiftnsfilemanageralamofire

Download Image Using Alamofire and Save to Application Support on Mac


The Alamofire readme indicates that you can download and save a file like this:

let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)

Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)

...but I want to change the location where it is saved. How do I alter .DocumentDirectory to be my app's Application Support path on Mac OS X?

I can generate my app's local NSURL path like this:

let path = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)[0] as NSURL
let newPath = path.URLByAppendingPathComponent("MyApp/user-profile.png")

I'm unclear on how to use this with Alamofire's suggestedDownloadDestination.

Any ideas?


Solution

  • suggestedDownloadDestination will try to find an available directory, but in your case you already know the full path so you don't need it.

    Just create a closure with your path:

    let path = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)[0] as NSURL
    let newPath = path.URLByAppendingPathComponent("MyApp/user-profile.png")
    Alamofire.download(.GET, "http://httpbin.org/stream/100", { _ in newPath })