这里是手动功能将您的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)
}
}
}
感谢。
您是否想将自定义名称的下载数据保存到应用的文档目录? –
是的,我想在文档目录中保存具有不同名称的文件 – mirza
请查看我的答案。如果您遇到任何问题,请告诉我。 –