2016-10-07 198 views
7

在旧版本的Alamofire中。这是我下载文件的方式使用Alamofire 4.0下载文件(Swift 3)

let destinationPath = Alamofire.Request.suggestedDownloadDestination(directory: .documentDirectory, domain: .userDomainMask); 

    Alamofire.download(.GET, urlString, destination: destinationPath) 
     .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in 
//    print(totalBytesRead) 
     } 
     .response { request, response, _, error in 

      let downloadedFilePath = destinationPath(URL(string: "")!, response!); 

      NSUserDefaultsHelper.saveURL(downloadedFilePath, key: urlString); 

      completion(downloadedFilePath, true); 
    } 

但是现在在新版本中,我的代码完全无法使用,并且在Alamofire库中没有类似的功能。

有什么想法吗?

+3

当我谷歌'下载文件使用Alamofire 4.0(SWIFT 3)',我得到一个链接到Alamofire的官方文档其中有一个[示例](https://github.com/Alamofire/Alamofire#downloading-数据到文件)如何下载文件。这没有用吗? –

回答

21

我用这个语句:

let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) 

Alamofire.download(
    url, 
    method: .get, 
    parameters: parameters, 
    encoding: JSONEncoding.default, 
    headers: nil, 
    to: destination).downloadProgress(closure: { (progress) in 
     //progress closure 
    }).response(completionHandler: { (DefaultDownloadResponse) in 
     //here you able to access the DefaultDownloadResponse 
     //result closure 
    }) 

更多细节Alamofire docs about Migration to 4.0阅读更多:

+0

响应中的代码块是DefaultDownloadResponse,我在获取最终的'downloadedFilePath'时遇到问题 – JayVDiyk

+0

实际下载的文件路径是'destination + nameOfTheFile',不是吗? – pedrouan

+0

是的,但如果你看我的代码,文件名是由Alamofire自动生成的。这就是我使用destinationPath函数获取完整路径的原因。 – JayVDiyk

6

有几种增强功能Alamofire 4.第一个是目标闭合的可选性。现在,默认情况下,目标闭包为零,这意味着文件不会在文件系统上的任何位置移动,并返回临时URL。

这是默认执行: -

Alamofire.download(urlString).responseData { response in 
    print("Temporary URL: \(response.temporaryURL)") 
} 

这是我的代码来下载文件,Alamofire 4.0返回该文件的目标网址: -

let destination: DownloadRequest.DownloadFileDestination = { _, _ in 
     var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 
     documentsURL.appendPathComponent("duck.png") 
     return (documentsURL, [.removePreviousFile]) 
    } 

    Alamofire.download(url, to: destination).responseData { response in 
    if let destinationUrl = response.destinationURL ? { 
     completionHandler(destinationUrl) 
    } 
} 
+0

为什么使用'documentsURL,[.removePreviousFile]' –

3

斯威夫特3 Alamofire(4.4.0 ):

.plist添加键“App Transport Security Settings-> Allow Arbitrary Loads-> Yes”如果您复制并粘贴以下代码:

import Alamofire 

    let destination = DownloadRequest.suggestedDownloadDestination() 

    Alamofire.download("http://zmp3-mp3-lossless-te-zmp3-bdhcm-1.zadn.vn/151e407bb43f5d61042e/1223048424027738068?key=f-zMo3GZKlhVibnvGMsMuQ&expires=1495726053&filename=See%20You%20Again%20-%20Wiz%20Khalifa%20Charlie%20Puth%20(NhacPro.net).flac", to: destination).downloadProgress(queue: DispatchQueue.global(qos: .utility)) { (progress) in 
     print("Progress: \(progress.fractionCompleted)") 
    } .validate().responseData { (response) in 
     print(response.destinationURL!.lastPathComponent) 
    } 
1

下载与Alamofire 4.0雨燕4.x的

MP3文件,由于几乎所有的样本似乎是有关下载图像或JSON文件,我花了时间,找到合适的解决方案。
我会在这里分享,希望能帮助别人节省一些时间。

func startDownload(audioUrl:String) -> Void { 
    let fileUrl = self.getSaveFileUrl(fileName: audioUrl) 
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in 
     return (fileUrl, [.removePreviousFile, .createIntermediateDirectories]) 
    } 

    Alamofire.download(audioUrl, to:destination) 
     .downloadProgress { (progress) in 
      self.progressLabel.text = (String)(progress.fractionCompleted) 
     } 
     .responseData { (data) in 
      self.progressLabel.text = "Completed!" 
    } 
} 

func getSaveFileUrl(fileName: String) -> URL { 
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 
    let nameUrl = URL(string: fileName) 
    let fileURL = documentsURL.appendingPathComponent((nameUrl?.lastPathComponent)!) 
    NSLog(fileURL.absoluteString) 
    return fileURL; 
}