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

时间:2016-10-05 08:59:09

标签: ios swift swift3 alamofire

我正在尝试将let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" formatter.locale = Locale(identifier: "us") var date = formatter.date(from: date_str)! print(date) 用于Alamofire4。我需要下载。Swift3文件并将它们保存到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) } } 中的文件。我还注意到,对于我尝试下载的不同文件,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

我如何检查m4a.mp4?

5 个答案:

答案 0 :(得分:13)

你为什么要表现.validate?下载后,您不会在当前代码中存储任何数据。 Alamofire allows you to store a file directly after download:

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)
    }
}

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

答案 1 :(得分:7)

  

Swift 3.x和Alamofire 4.x版本

当然,Alamofire发布的Alamofire示例本身就有错误。由于fileURL返回Void,因此无法将其用作return语句中的参数。

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

修改
如果您想知道文件的类型,只需抓住最后一个组件部分并将String转换为NSString,因为NSString具有这些功能。

//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!)
            }
        }

输出

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

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

答案 2 :(得分:1)

目标:从服务器下载的文件(如gif,pdf或zip)将存储在指定的文件夹名称中。

如果你想存储你自己的文件夹结构,比如名字是" ZipFiles"

打电话。

self downloadZipFileFromServer(downloadFolderName: "ZipFiles");

下载的zip数据存储在文档/ ZiFiles / abc.zip

这只是在文档中创建一个文件夹

func createFolder(folderName:String)

Alamofire 4
Swift 4
/******Download image/zip/pdf  from the server and save in specific Dir********/
func downloadZipFileFromServer(downloadFolderName: string)
{
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var fileURL = self.createFolder(folderName: downloadFolderName)
        let fileName = URL(string : "www.xymob.com/abc.zip")
        fileURL = fileURL.appendingPathComponent((fileName?.lastPathComponent)!)
        return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }
    Alamofire.download("www.xymob.com/abc.zip", to: destination).response(completionHandler: { (DefaultDownloadResponse) in                
        print("res ",DefaultDownloadResponse.destinationURL!);
    })
}        

func createFolder(folderName:String)->URL
{
    var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory: String = paths[0] as? String ?? ""
    let dataPath: String = URL(fileURLWithPath: documentsDirectory).appendingPathComponent(folderName).absoluteString
    if !FileManager.default.fileExists(atPath: dataPath) {
        try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
    }
    let fileURL = URL(string: dataPath)
    return fileURL!
}

答案 3 :(得分:1)

Swift 5-Alamofire 5.1。 这是方法。

let destination: DownloadRequest.Destination = { _, _ in
        let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("image.png")

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

    AF.download("https://httpbin.org/image/png", to: destination).response { response in
        debugPrint(response)

        if response.error == nil, let imagePath = response.fileURL?.path {
            let image = UIImage(contentsOfFile: imagePath)
        }
    }

答案 4 :(得分:1)

虽然这个问题比较老,
我已经在 Swift 5 上重写并测试了它

import Foundation
import Alamofire

class DownloadFileService {
    
    static func downloadFile(using url: URL, completion: @escaping () -> Void) {
        let fileName = url.lastPathComponent
        
        let destination: DownloadRequest.Destination = { _, _ in
            var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            
            documentsURL.appendPathComponent(fileName)
            return (documentsURL, [.removePreviousFile])
        }
        
        AF.download(url, to: destination).response { response in
            print(response)
            completion()
        }
    }
    
}