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

我以前一直在从Parse后端检索图像,使用以下代码行在UI ImageView中的应用程序中显示:
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修复技巧提示“as!”改变所以我添加!,但后来我得到错误:

‘AnyObject?’ is not convertible to ‘PFFile’

使用’getDataInBackgroundWithBlock’部分,我也得到错误:

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

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

解决方法

PFUser.currentUser()返回可选类型(Self?).因此,您应该将返回值解包为按下标访问元素.
PFUser.currentUser()?["picture"]

下标得到的值也是可选类型.因此,您应该使用可选绑定来转换值,因为类型转换可能会失败.

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

getDataInBackgroundWithBlock()方法的结果块的参数都是可选类型(NSData?和NSError?).所以你应该为参数指定可选类型,而不是NSData和NSError.

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...