小编典典

Xcode:下载mp3文件

swift

我正在编写一个应用程序,可以在其中输入来自Web的mp3文件的URL,当我单击下载时,该应用程序会将其下载到应用程序中。有人能帮我吗
?我是ios开发的新手。我正在尝试学习Swift


阅读 308

收藏
2020-07-07

共1个答案

小编典典

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()
    }
}
2020-07-07