I am trying to download a file use Foreground internet operation . it successfully download but problem is file not exist in the directory
Code :
let urlString = "https://joycemusic1.files.wordpress.com/2015/07/fight-song-rachel_platten.pdf"
let filePath = "Documents/"
if let url = NSURL(string: urlString){
let tast = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { (NSURL, NSURLResponse, NSError) in
if let error = NSError{
print(error)
}
if let locationString = NSURL , let fileLocation = locationString.path {
//print(fileLocation)
let fileExists = NSFileManager().fileExistsAtPath("fight-song-rachel_platten.pdf")
if fileExists == true{
try! NSFileManager.defaultManager().moveItemAtPath(fileLocation, toPath: filePath)
}
}
})
tast.resume()
}
download file path is:
/Users/twilight/Library/Developer/CoreSimulator/Devices/80CCC33B-817F-46C7-A65E-2B1CAA86D940/data/Containers/Data/Application/43CB754B-4096-47B1-9A97-32D1657E426B/tmp/CFNetworkDownload_EoIzdN.tmp
No file found
There are two major mistakes.
You have to check if the file exists at fileLocation
let fileExists = NSFileManager().fileExistsAtPath(fileLocation)
The file path Documents/
doesn't exist at all. You have to get the URL to the documents folder in the sandbox with
let documentsURL = try! FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
(sorry, that's Swift 3 code)
Not related to the errors, but after printing the error write return
to exit the completion block.
Never use the class names NSURL
, NSURLResponse
, NSError
as variable names, use url
, response
, error
instead.