2

我正在创建一个解析应用程序,其中用户可以在注册时选择个人资料图片。这是代码。

    var profilePictures = PFObject(className: "ProfilePictures")
    let imageData = UIImagePNGRepresentation(self.profileImage.image)
    let imageFile = PFFile(name:"image.png", data:imageData)

    profilePictures["profilePhoto"] = imageFile
    profilePictures["user"] = usernameField.text
    profilePictures.save()

后来我有一个屏幕,其中 UIImageView 需要填充所选的个人资料图片。

这一直有效,直到应用程序本身完全停止并重新启动。

然后发现 PFFile 为 nil,我收到错误“在展开可选值时意外发现 nil”。

这是显示图片的代码。

     override func viewDidAppear(animated: Bool) {
    var query = PFQuery(className: "ProfilePictures")
    query.whereKey("user", equalTo: PFUser.currentUser()?.username)
    query.findObjectsInBackgroundWithBlock({
        (success, error) -> Void in
        let userImageFile = profilePictures["profilePhoto"] as! PFFile  
        //error is on the above line

        userImageFile.getDataInBackgroundWithBlock({
            (imageData: NSData?, error) -> Void in
            var image = UIImage(data: imageData!)
            self.profileImage.image = image
        })


    })

}
4

2 回答 2

2

由于某种原因,您没有正确设置 userImageFile。它似乎是零。我会检查 Parse 控制台以确认您在 PFile 中有图像。在任何情况下,使用“if let”来避免展开问题可能会更聪明。如果没有保存 PFile,这将无法解决问题,因为如下所述,您应该使用 saveInBackground 并使用通知来确认您已准备好进行检索。

if let userImageFile = profilePictures["profilePhoto"] as! PFFile  {
    //error is on the above line

    userImageFile.getDataInBackgroundWithBlock({
        (imageData: NSData?, error) -> Void in
        var image = UIImage(data: imageData!)
        self.profileImage.image = image
    })
}
于 2015-06-11T17:04:49.460 回答
0

您的错误可能在于保存:

let imageFile = PFFile(name:"image.png", data:imageData)
profilePictures["profilePhoto"] = imageFile
profilePictures.save()

您正在保存一个带有指向新未保存 PFFile 的指针的对象,这会导致错误。您应该首先执行 imageFile.saveInBackground,并使用回调将 imageFile 分配到 profilePictures,然后保存 profilePictures。

您可以通过在 Parse 的数据存储中查看您的 profilePictures 对象上的键“profilePhoto”没有值来确认这一点

于 2015-06-11T16:58:16.220 回答