在我重新启动应用程序之前,文档目录中的 writeToFile 不会更新

writeToFile in documents directory not updating until I restart the app

我正在使用我的应用程序的文档目录在本地缓存图像,但是当我去访问它们时,它们在我关闭应用程序并重新打开之前不会更新。

这是我的存档:

    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

这可能对你有帮助....

    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

中的项目