iOS - 在 UIImageView 中检索并显示来自 Parse 的图像(Swift 1.2 错误)

iOS - Retrieve and display an image from Parse in UIImageView (Swift 1.2 Error)

我之前一直在使用以下代码行从我的 Parse 后端检索图像以显示在我的应用程序中的 UIImageView 中:

let userPicture = PFUser.currentUser()["picture"] as PFFile

userPicture.getDataInBackgroundWithBlock { (imageData:NSData, error:NSError) -> Void in
    if (error == nil) {

            self.dpImage.image = UIImage(data:imageData)

    }
}

但我收到错误消息:

'AnyObject?' is not convertible to 'PFFile'; did you mean to use 'as!' to force downcast?

Apple 的 'helpful' 修复提示建议进行 "as!" 更改,所以我添加了 !,但随后出现错误:

'AnyObject?' is not convertible to 'PFFile'

对于 'getDataInBackgroundWithBlock' 部分,我也得到错误:

Cannot invoke 'getDataInBackgroundWithBlock' with an argument list of type '((NSData, NSError) -> Void)'

有人可以解释一下如何使用 Swift 1.2 从 Parse 正确检索照片并在 UIImageView 中显示它吗?

PFUser.currentUser() returns 可选类型 (Self?)。所以你应该打开 return 值以通过下标访问元素。

PFUser.currentUser()?["picture"]

并且下标得到的值也是可选类型。所以你应该使用可选绑定来转换值,因为类型转换可能会失败。

if let userPicture = PFUser.currentUser()?["picture"] as? PFFile {

getDataInBackgroundWithBlock()方法结果块的参数都是可选类型(NSData?NSError?)。因此,您应该为参数指定可选类型,而不是 NSDataNSError.

userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in

修改以上所有问题的代码如下:

if let userPicture = PFUser.currentUser()?["picture"] as? PFFile {
    userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
        if (error == nil) {
            self.dpImage.image = UIImage(data:imageData)
        }
    }
}