使用Alamofire.download()的示例工作得很好,但是在如何访问最终下载的文件方面没有任何细节。我可以根据我设置的目标和我提出的原始文件请求来确定文件的位置和名称,但我假设应该有一个值可以访问,以便在响应中获得完整的最终下载路径和文件名。
如何访问该文件的名称,以及如何知道它是否成功保存?我可以在实际的Alamofire代码中看到委托方法,这些方法似乎处理对下载过程的委托完成调用,但我/我如何访问.response块中的文件详细信息?
发布于 2014-10-16 21:04:35
Alamofire自述文件上的示例实际上有文件路径,所以我在代码的其他地方使用一个单独的变量来获取它。这并不是很优雅,我希望有办法在回复中得到这些信息,但就目前而言,这是完成任务:
var fileName: String?
var finalPath: NSURL?
Alamofire.download(.GET, urlToCall, { (temporaryURL, response) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
fileName = response.suggestedFilename!
finalPath = directoryURL.URLByAppendingPathComponent(fileName!)
return finalPath!
}
return temporaryURL
})
.response { (request, response, data, error) in
if error != nil {
println("REQUEST: \(request)")
println("RESPONSE: \(response)")
}
if finalPath != nil {
doSomethingWithTheFile(finalPath!, fileName: fileName!)
}
}
发布于 2015-11-20 21:56:58
Swift 2.1,稍微简单一点:
var localPath: NSURL?
Alamofire.download(.GET,
"http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v",
destination: { (temporaryURL, response) in
let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pathComponent = response.suggestedFilename
localPath = directoryURL.URLByAppendingPathComponent(pathComponent!)
return localPath!
})
.response { (request, response, _, error) in
print(response)
print("Downloaded file to \(localPath!)")
}
)
仍然很难理解他们为什么要使用闭包来设置目标路径..。
发布于 2015-06-21 05:49:56
我花了大约8个小时寻找这个答案。下面的解决方案适用于我,基本上我链接到下载方法来显示图像。在下面的示例中,我下载了一个知道Facebook ID的用户的配置文件图像:
let imageURL = "http://graph.facebook.com/\(FBId!)/picture?type=large"
let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
(temporaryURL, response) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
var localImageURL = directoryURL.URLByAppendingPathComponent("\(self.FBId!).\(response.suggestedFilename!)")
return localImageURL
}
return temporaryURL
}
Alamofire.download(.GET, imageURL, destination).response(){
(_, _, data, _) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
var error: NSError?
let urls = NSFileManager.defaultManager().contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: nil, options: nil, error: &error)
if error == nil {
let downloadedPhotoURLs = urls as! [NSURL]
let imagePath = downloadedPhotoURLs[0] // assuming it's the first file
let data = NSData(contentsOfURL: imagePath)
self.viewProfileImage?.image = UIImage(data: data!)
}
}
}
https://stackoverflow.com/questions/26307170
复制相似问题