Xcode:下载mp3文件

Xcode:下载mp3文件,xcode,swift,Xcode,Swift,我正在写一个应用程序,我可以从网上输入一个mp3文件的URL,当我点击下载时,应用程序将在应用程序中下载它。有人能帮我吗? 我是ios开发新手。我正在努力学习SwiftXcode 8•Swift 3 if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") { // then lets create your document folder url let document

我正在写一个应用程序,我可以从网上输入一个mp3文件的URL,当我点击下载时,应用程序将在应用程序中下载它。有人能帮我吗?
我是ios开发新手。我正在努力学习Swift

Xcode 8•Swift 3

if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {

    // then lets create your document folder url
    let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    // lets create your destination file url
    let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
    print(destinationUrl)

    // to check if it exists before downloading it
    if FileManager.default.fileExists(atPath: destinationUrl.path) {
        print("The file already exists at path")

        // if the file doesn't exist
    } else {

        // you can use NSURLSession.sharedSession to download the data asynchronously
        URLSession.shared.downloadTask(with: audioUrl) { location, response, error in
            guard let location = location, error == nil else { return }
            do {
                // after downloading your file you need to move it to your destination url
                try FileManager.default.moveItem(at: location, to: destinationUrl)
                print("File moved to documents folder")
            } catch {
                print(error)
            }
        }.resume()
    }
}

非常感谢。除了writeToURL不起作用外,大多数代码都起作用。我用writeToFile,这对我来说很有用me@Leo如果我必须提供多个可下载文件的选项,那么?问题是urlsForDirectory是一个url数组,我如何为它分配索引,您的代码只拾取第一个索引,然后将其附加到数组的最后一个组件。如果我向它添加.index,那么它会将它转换为不识别URL数组的Int类型