我正在使用Alamofire从服务器下载文件。但我想以不同的方式命名它,就像我们从网上下载文件一样,并且可以按照我们的意愿命名,同样如何在swift中实现
我使用以下代码: -
Alamofire.download(fileUrl, to: destination)
.downloadProgress { progress in
print("Download Progress:---------- \
(progress.fractionCompleted)")
}
.responseData { response in
print(response.request)
print(response.response)
print(response.temporaryURL)
print(response.destinationURL)
print(response.error)
}
不希望使用alamofire重命名或覆盖文件。还有其他方法
答案 0 :(得分:0)
以下是将您的Data
保存到 DocumentDirectory 并使用您提供的名称的实用功能。此方法有一个call back
,它将在执行保存操作后调用,它将返回图像保存在目录中的路径。此函数用Swift 3
。
func saveImageInDocDirectory(data: Data?, fileName: String?, successblock: @escaping (_ path: String?) -> Void) { // To add the image to cache for given identifier.
let paths = NSSearchPathForDirectoriesInDomains( .documentDirectory, .userDomainMask, true)[0] as String
let path = paths.appending("/\(fileName!)")
if !FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.createDirectory(at: URL(fileURLWithPath: path), withIntermediateDirectories: false, attributes: nil)
} catch {
print("Error creating images folder in Cache dir: \(error)")
}
}
if (filemgr.fileExists(atPath: path)) {
try! filemgr.removeItem(atPath: path)
} else {
do {
try data?.write(to: URL(fileURLWithPath: path, isDirectory: false))
successblock(path)
} catch {
successblock(nil)
print("Error while caching the data in cache folder.")
}
}
}
您可以将此方法称为
Alamofire.download(fileUrl, to: destination)
.downloadProgress { progress in
print("Download Progress:---------- \
(progress.fractionCompleted)")
}
.responseData { response in
print(response.request)
print(response.response)
print(response.temporaryURL)
print(response.destinationURL)
print(response.error)
if let data = response.result.value {
self.saveImageInDocDirectory(data: data, fileName: "YourFile", successblock: { (path) in
print(path)
}
}
}
感谢。