這裏是手動功能將您的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
請查看我的答案。如果您遇到任何問題,請告訴我。 –