从Parse检索PFFile的问题

时间:2015-06-11 16:50:23

标签: ios swift parse-platform pffile

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

    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
        })


    })

}

2 个答案:

答案 0 :(得分:2)

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

{{1}}

答案 1 :(得分:0)

您的错误可能是保存:

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

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

您可以通过查看Parse的数据存储区确认您的profilePictures对象上的密钥“profilePhoto”没有值

相关问题