我正在使用我的应用程序的文档目录在本地缓存图像,但是当我去访问它们时,在我关闭应用程序并重新打开之前它们不会更新。
这是我的保存:
var readPath = ""
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
readPath = dirPath.stringByAppendingPathComponent("\(user).png")
UIImagePNGRepresentation(imageView.image).writeToFile(readPath, atomically: true)
}
}
}
这是我的检索:
var readPath = ""
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
readPath = dirPath.stringByAppendingPathComponent("\(user).png")
//UIImagePNGRepresentation(imageView.image).writeToFile(readPath, atomically: true)
}
}
}
let cachedImage = UIImage(named: readPath)
if (cachedImage != nil)
{
println("cached")
self.userPictures.append(cachedImage!)
}
出于某种原因,直到我重置应用程序,这些资源才可用。
有人能说清楚为什么会这样吗?
返回到cachedImage的图像是我之前保存到该特定路径的图像btw
答案 0 :(得分:0)
这可能对你有帮助....
let fileManager = NSFileManager.defaultManager()
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var getImagePath = paths.stringByAppendingPathComponent("\(fileName).png")
if (fileManager.fileExistsAtPath(getImagePath))
{
println("FILE AVAILABLE");
//Pick Image and Use accordingly
var imageis: UIImage = UIImage(contentsOfFile: getImagePath)!
self.image = imageis // UIImageView Class
let datas: NSData = UIImagePNGRepresentation(imageis)
}
else
{
println("FILE NOT AVAILABLE");
let getImage = UIImage(data: self.data)
self.image = getImage
var filePathToWrite = "\(paths)/\(fileName).png"
var imageData: NSData = UIImagePNGRepresentation(self.image)
fileManager.createFileAtPath(filePathToWrite, contents: imageData, attributes: nil)
}
检查Github
中的项目