意外发现文件的 UIImage 内容为零

UIImage content of file unexpectedly found nil

我正在尝试加载保存在文档目录中的图像。如果我打印路径,我可以看到有图像,但是,当我尝试将路径分配给 UIImage 时,应用程序崩溃:

static func callSavedProfileImage() -> UIImage{
        //let profilePictureUser = NSUserDefaults.standardUserDefaults()
        let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
        let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask
        let paths            = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)

        var newImage = UIImage!()
        if paths.count > 0
        {
            let dirPath = paths[0]

            let readPath = (dirPath as NSString).stringByAppendingPathComponent("ProfilePic.png")

            print(readPath) ///var/mobile/Containers/Data/Application/C9F738C1-F747-4C1D-ADBE-251F168444D4/Documents/ProfilePic.png

            let savedProfilePicture = readPath

            if let savedImage = UIImage(contentsOfFile: savedProfilePicture) {
                newImage = savedImage
            }

        }


        print(newImage)

        return newImage
    }

知道为什么吗?

var newImage = UIImage!()

应该是

var newImage = UIImage()

当您声明 UIImage!() 时,它会创建一个 隐式解包的 Optional 如果在 nil 时解包,它将崩溃。

去掉!就可以创建一个普通的UIImage,这样就不会因为找不到图片而崩溃了。