【问题标题】:File download with Alamofire使用 Alamofire 下载文件
【发布时间】:2015-10-01 13:19:14
【问题描述】:

我正在将文件下载到这样的自定义文件路径:

let tempFilePath = self.makeTempFilePath()
Alamofire.download(.GET, downloadURL) { temporaryURL, response in
    return tempFilePath
}

我如何知道下载何时完成以及成功/失败状态?我试过responseData闭包但result参数总是显示为“失败”。

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    恐怕您可以使用 Alamofire 文档中解释的Downloading a File w/Progress,如下所示:

    Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
         .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
             print(totalBytesRead)
    
             // This closure is NOT called on the main queue for performance
             // reasons. To update your ui, dispatch to the main queue.
             dispatch_async(dispatch_get_main_queue) {
                 print("Total bytes read on main queue: \(totalBytesRead)")
             }
         }
         .responseData { response in
             print(response)
         }
    

    通过上面的代码,您可以知道totalBytesExpectedToReadtotalBytesRead 并部分了解两者之间的区别,以检查文件是否已下载。

    在任何情况下,您也可以使用 Alamofire 文档中解释的Accessing Resume Data for Failed Downloads,以防下载过程中出现任何故障。

    希望对你有所帮助。

    【讨论】:

    • 谢谢。已经试过了。即使totalBytesRead 等于totalBytesExpectedToRead,该文件仍然无法访问。
    • 您改为使用response 序列化程序并检查error 是否为nil。如果是,则下载成功。 responseData 序列化程序在成功的情况下总是会失败,因为从会话委托返回的 data 将是 nil。数据写入文件,而不是内存。此外,自述文件中的文档已更新。
    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多