gpt4 book ai didi

ios - 使用 Swift 以不同名称保存文件

转载 作者:行者123 更新时间:2023-11-30 12:29:15 25 4
gpt4 key购买 nike

我正在使用 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 重命名或覆盖文件。还有其他方法吗

最佳答案

这里是使用您指定的名称将您的数据保存到DocumentDirectory中的实用函数。该方法有一个回调,它会在执行保存操作后调用,它将返回图像保存在目录中的路径。该函数用 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)

}
}

}

谢谢。

关于ios - 使用 Swift 以不同名称保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43798452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com