我需要在本地上传图片并稍后获取。现在我的问题是我可以在启动应用程序后第一次尝试时存储并获取正确的图像。但是当我尝试上传相同名称但图像不同的同一文件时,我得到的是先前存储的图像。
这是我的代码:
Map<String, List<String>> collect = list.stream()
.map(string -> string.split(" "))
.collect(Collectors.groupingBy(o -> o[0],
Collectors.mapping(o -> o[1],
Collectors.toList())));
我将URL称为String,
let i = "image1"
let str = String(i).appending(".png")
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(str)
if fileManager.fileExists(atPath: paths) {
do {
try fileManager.removeItem(atPath: paths)
print("old image has been removed")
} catch {
print("an error during a removing")
}
}
let imageData = UIImageJPEGRepresentation(uploadingImage!, 0.5)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
有人请帮我在我的代码中找到问题...
答案 0 :(得分:0)
尝试使用
imageData?.write(to: URL(fileURLWithPath: paths))
而不是
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
答案 1 :(得分:0)
我不明白为什么你的代码不起作用。但是,安全替换文件所需的工作流程为:
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(atPath: path)
} catch let error {
print("Cannot delete file on device: \(path): \(error)")
return
}
}
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)