ChikabuZ ChikabuZ - 4 months ago 102
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: "http://www.sa.is/media/1039/example.pdf"))
let session = AFHTTPSessionManager()

var progress: NSProgress?

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

downloadTask.resume()
}

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


What I doing wrong?

Rob Rob
Answer

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)
        .URLByAppendingPathComponent("test.pdf")
}

Or in Swift 3:

var pathUrl: URL {
    return try! FileManager.default.urlForDirectory(.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent("test.pdf")
}
Comments