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

时间:2016-01-11 13:47:10

标签: ios swift uiimage

我正在尝试加载已保存在Document目录中的图像。如果我打印路径,我可以看到有图像但是,当我试图将路径指定给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
    }

知道为什么吗?

1 个答案:

答案 0 :(得分:1)

var newImage = UIImage!()

应该是

var newImage = UIImage()

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

只需删除!即可创建正常的UIImage,如果无法找到图像,它就不会崩溃。