Search code examples
iosswiftdownloadnsurlconnectionnsurl

Not downloading files to NSDocumentsDirectory correctly?


I want to download files to my NSDocumentsDirectory. I grab a url that is a download link and that url is stored into a variable called url Here is my code to perform the download and store it into the Documents Directory so:

let data = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: &response,error: &error)

if data != nil && error == nil{ 
  var documentsDirectoryUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL
  documentsDirectoryUrl = documentsDirectoryUrl.URLByAppendingPathComponent(url.lastPathComponent)
  //Hold this file as an NSData and write it to the new location
  let fileData = NSData(contentsOfURL: NSURL(string:url)!)

  fileData!.writeToURL(documentsDirectoryUrl, atomically: false)   // true
  println("\(data!.length) bytes of data was written to Documents Directory.")
}
else if data!.length == 0 && error == nil{
  println("No data was returned")
}
else if error != nil{
  println("Error happened = \(error)");
}

Since the files I'm downloading are music files, when I try to play audio from these music files, I get an error when I try to access the file's path because that file's path is set to nil. I think it's an issue with downloading the file because I had the code working before but then I changed how I downloaded the music files and the code seemed to break. Any help would be appreciated. Thanks!


Solution

  • import UIKit
    
    
    let documentsDirectoryUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL
    
    var error:NSError?
    var response:NSURLResponse?
    
    let data = NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: NSURL(string: "https://i.sstatic.net/Xs4RX.jpg")!), returningResponse: &response, error: &error)
    
    if let data = data where error == nil {
        let destinationUrl = documentsDirectoryUrl.URLByAppendingPathComponent(response!.suggestedFilename!)
        data.writeToURL(destinationUrl, atomically: true)   // true
        println("\(data.length) bytes of data was written to Documents Directory.")
    
    }
    if let error = error {
        println(error.description)
    }