如何在Alamofire 4中下载文件并保存到Documents目录?

Kex*_*Kex 11 ios swift alamofire swift3

我试图用Alamofire4Swift3.我需要下载.mp3文件并将它们保存到Documents目录中.目前的代码是这样的:

func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {


        let fileManager = FileManager.default
        let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let audioFullURL = String.ensureFullURLPath(url)


        alamoManager.download(audioFullURL)
            .validate { request, response, temporaryURL, destinationURL in

                var pathComponent = response.suggestedFilename!
                if pathComponent == "m4a.mp4" {
                    // Due to the old Android audio files without a filename
                    // Assign a unique name so audio files don't overwrite each other
                    pathComponent = "\(NSUUID().uuidString).mp4"
                }
                let localURL = directoryURL.appendingPathComponent(pathComponent)

                if response.statusCode == 200 {
                    completion?(.success, localURL)
                } else {
                    completion?(.failure, nil)
                }
                return .success
            }

            .responseJSON { response in
                debugPrint(response)
                print(response.temporaryURL)
                print(response.destinationURL)
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是我实际上无法从localURL保存后访问文件.我还注意到,localURL对于我尝试下载的不同文件,它们会完全相同(也许它们会被覆盖?).例如:file:///Users/testuser/Library/Developer/CoreSimulator/Devices/D4254AEA-76DD-4F01-80AF-F1AF3BE8A204/data/Containers/Data/Application/29755154-DD21-4D4C-B340-6628607DC053/Documents/file1.mp3

我在这里做错了什么想法?

编辑我的代码看起来像这样:

func downloadAudioFromURL(url: String, completion: ((_ status: ResponseStatus, _ audioLocalURL: URL?) -> Void)?) {

        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

            documentsURL.appendPathComponent("Audiofile.mp3")
            return (documentsURL, [.removePreviousFile])
        }

        Alamofire.download(url, to: destination).response { response in

            if let localURL = response.destinationURL {

                completion?(.success, localURL)

            } else {

                completion?(.failure, nil)
            }

        }
}
Run Code Online (Sandbox Code Playgroud)

我怎么检查m4a.mp4呢?

ezc*_*ing 14

你为什么表演.validate?下载后,您不会在当前代码中存储任何数据. Alamofire允许您在下载后直接存储文件:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendPathComponent("pig.png")

    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(urlString, to: destination).response { response in
    print(response)

    if response.result.isSuccess, let imagePath = response.destinationURL?.path {
        let image = UIImage(contentsOfFile: imagePath)
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便提一下,您在download方法中提供的下载路径是Documents目录的本地URL,而不是服务器的URL.


Raj*_*ari 8

Swift 3.x和Alamofire 4.x版本

当然Alamofire,Alamofire发布的例子本身就有错误.因为fileURL返回Void它不能用作return语句中的参数.

.createIntermediateDirectories如果您不想要下载文件的任何目录,也可以从return语句的选项列表中删除

编辑
如果你想知道文件的类型,只要抓住最后的组成部分,转换StringNSStringNSString具有这些功能.

//audioUrl should be of type URL
let audioFileName = String((audioUrl?.lastPathComponent)!) as NSString

//path extension will consist of the type of file it is, m4a or mp4
let pathExtension = audioFileName.pathExtension

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

    // the name of the file here I kept is yourFileName with appended extension
    documentsURL.appendPathComponent("yourFileName."+pathExtension)
    return (documentsURL, [.removePreviousFile])
}

Alamofire.download("yourAudioUrl", to: destination).response { response in
            if response.destinationURL != nil {
                print(response.destinationURL!)
            }
        }
Run Code Online (Sandbox Code Playgroud)

输出是

file:///Users/rajan/Library/Developer/CoreSimulator/Devices/92B4AB6E-92C0-4864-916F-9CB8F9443014/data/Containers/Data/Application/781AA5AC-9BE7-46BB-8DD9-564BBB343F3B/Documents/yourFileName.mp3
Run Code Online (Sandbox Code Playgroud)

这是存储文件的实际路径.