使用Swift从服务器下载文件

7 nsfilemanager swift

嗨我有一大堆.mp3文件我想与NSFileManager一起使用并存储在documents文件夹中.有没有办法我可以在线下载.mp3文件,然后将它保存到文档文件夹?这就是我用于本地文件的内容.

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")
}
Run Code Online (Sandbox Code Playgroud)

Leo*_*bus 22

Xcode 8.3.2•Swift 3.1

if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
    // create your document folder url
    let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    // your destination file url
    let destination = 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, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("audio"),
                let location = location, error == nil
                else { return }
            do {
                try FileManager.default.moveItem(at: location, to: destination)
                print("file saved")
            } catch {
                print(error)
            }
        }).resume()
    }
}
Run Code Online (Sandbox Code Playgroud)