Dewan Payroda Dewan Payroda - 5 months ago 190
Swift Question

Download file path with NSFileManager

Hi I have a whole bunch of .mp3 files I want to use with NSFileManager and store in the documents folder. Is there a way I can download the .mp3 files online and then have it save to the documents folder? This is what I'm using for a local file.

let filemanager = NSFileManager.defaultManager()
let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
let destinationPath:NSString = documentsPath.stringByAppendingString("/Attention.mp3")

if (!filemanager.fileExistsAtPath(destinationPath)) {
var theError: NSError?
let fileForCopy = NSBundle.mainBundle().pathForResource("Attention",ofType:"mp3")
filemanager.copyItemAtPath(fileForCopy!,toPath:destinationPath, error: &theError)

if (theError == nil) {
println("The music files has been saved.")
} else {
println("Error")
}
} else {
println("The files already exist")
}

Answer

Xcode 8 (beta) • Swift 3.0

if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
    // create your document folder url
    let documentsUrl: URL! =  FileManager.default().urlsForDirectory(.documentDirectory, inDomains: .userDomainMask).first
    // your destination file url
    let destination: URL! = try? documentsUrl.appendingPathComponent(audioUrl.lastPathComponent!)
    print(destination)
    // check if it exists before downloading it
    if FileManager().fileExists(atPath: destination.path!) {
        print("The file already exists at path")
    } else {
        //  if the file doesn't exist
        //  just download the data from your url
        URLSession.shared().downloadTask(with: audioUrl, completionHandler: { (location, response, error) in
            // after downloading your data you need to save it to your destination url
            guard
                let httpURLResponse = response as? HTTPURLResponse where httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType where mimeType.hasPrefix("audio"),
                let location = location where error == nil
                else { return }
            do {
                try FileManager.default().moveItem(at: location, to: destination)
                print("file saved")
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }).resume()
    }
}