ChikabuZ ChikabuZ - 10 months ago 224
Swift Question

Download file with AFNetworking in swift

I want to download file from URL using AFNetworking in swift, and show downloading progress. I have this code, but it doesn't work:

func downloadPdf()
var request = NSURLRequest(URL: NSURL(string: ""))
let session = AFHTTPSessionManager()

var progress: NSProgress?

var downloadTask = session.downloadTaskWithRequest(request, progress: &progress, destination: {(file, responce) in self.pathUrl},
response, localfile, error in
println("response \(response)")


var pathUrl: NSURL
var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var url = NSURL(string: path.stringByAppendingPathComponent("file.pdf"))
return url

What I doing wrong?

Rob Rob

The issue is the pathUrl computed property. If you print the URL (rather than url.path), you'll see that your URL is not valid. That's because you're using NSURL(string:), and for file URLs, you should use NSURL(fileURLWithPath:). Thus:

var pathUrl: NSURL {
    let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
    let documentsURL = NSURL(fileURLWithPath: documentsFolder)
    return documentsURL.URLByAppendingPathComponent("file.pdf")

Or, even better, bypass the path altogether, and use URLForDirectory to get the .DocumentDirectory as a URL:

var pathUrl: NSURL {
    return try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)

Or in Swift 3:

var pathUrl: URL {
    return try! FileManager.default.urlForDirectory(.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)