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

4

我之前一直在从我的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?' 不能转换为 'PFFile'; 你是否想使用 'as!' 进行强制转换?
苹果公司提供了“有用”的修复提示,建议使用 "as!" 进行更改,但是之后我又收到了这个错误:
“AnyObject?”无法转换为“PFFile”
在 'getDataInBackgroundWithBlock' 部分,我还遇到了这个错误:
不能使用类型为 '((NSData,NSError) -> Void)' 的参数列表调用 'getDataInBackgroundWithBlock'
请问有人能够解释如何在 Swift 1.2 中正确地从 Parse 检索照片并将其显示在 UIImageView 中吗?
1个回答

10

PFUser.currentUser() 返回 optional 类型 (Self?)。因此,您需要解包返回值才能通过下标访问元素。

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

1
非常感谢!如果我有足够的声望,我会点赞的!Xcode 给我的唯一错误建议是在 imageData 后使用 '!' 标记,像这样:self.dpImage.image = UIImage(data: imageData!)。一旦我做出了这个改变,它就完美地工作了。 - Max
我无法在Swift2.1中使其工作,它返回nil。 - suisied

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接