我正在文档目录中保存firebase图像!!为了唯一性,我的文档目录名是firebase映像名!我检查了一个条件,如果在我的文档目录中不存在FialBasic图像名称,那么将该图像保存在文档目录中!!
我正在检查这个firebase名称是否意味着它保存在文档目录中,然后它获取文档目录映像如果不是,那么它从firebase获取映像!!
问题是当我试图获取图像时:-
(1)例如:-Firebase Image name为1.jpg。
(2)文档目录保存firebase名称为1.jpg的图像。
(3)现在我将firebase图像更改为其他,但它保存为名称1.jpg。
(4)当我试图获取图像,因为1.jpg已经在文档目录中,这就是为什么它不返回我更新的图像,它显示我以前的1.jpg图像!!
我怎样才能解决这个问题。谢谢您
保存并获取图像代码:-
func saveImageDocumentDirectory(imageName: String){
let documentPath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let imgURL = documentPath.appendingPathComponent(imageName, isDirectory: true)
if !FileManager.default.fileExists(atPath: imgURL.path){
do{
let image = UIImage(named: imgURL.path)
try image?.pngData()?.write(to: imgURL)
}catch let err{
print("error in save:\(err.localizedDescription)")
}
}
}
func getDocumentImage(imageName: String, firebaseImgURL: URL, imgView:UIImageView){
let documentPath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let imgURL = documentPath.appendingPathComponent(imageName, isDirectory: true)
let image = UIImage(contentsOfFile: imgURL.path)
if image != nil{
imgView.image = image
}else{
imgView.kf.setImage(with: firebaseImgURL)
}
}
最佳答案
请尝试下面的代码
Save Data
let placeholderURL: URL =
getDocumentDirectoryPath()!.appendingPathComponent("\(imageName.JPG)/",
isDirectory: true)
let fileExists: Bool = FileManager.default.fileExists(atPath: placeholderURL.path )
if !fileExists {
let thumbnailImageURL = URL(string: firebaseURL)
var placeholderData: Data? = nil
if let url = url {
do {
placeholderData = try Data(contentsOf: (thumbnailImageURL ?? nil)!)
} catch {
print("Unable to load data: \(error)")
}
}
if urlData != nil {
do {
//saving is done on main thread
try placeholderData?.write(to: URL(fileURLWithPath: placeholderURL.path) , options: .atomic)
} catch {
print(error)
}
}
}
检索图像
let thumbnailURL: URL = getDocumentDirectoryPath()!.appendingPathComponent("\("imageName.JPG")/", isDirectory: true)
let fileExists: Bool = FileManager.default.fileExists(atPath: thumbnailURL.path)
var urlThumbnail:URL? = nil
if fileExists {
urlThumbnail = URL(fileURLWithPath: thumbnailURL.path)
} else {
urlThumbnail = URL(string: firebaseURL)
}
图像视图中的Sat图像
self.imgtemp.sd_setImage(with: urlThumbnail, placeholderImage: UIImage(named: "placeholder.png"))
关于ios - 无法在Swift 4 iOS中将正确的Firebase图片保存在文档目录中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55148616/