问题描述
我以前从Parse后端检索图像,使用以下代码行在UIImageView内的应用程序中显示:
I have previously been retrieving an image form my Parse backend to display in my app inside a UIImageView using the following lines of code:
let userPicture = PFUser.currentUser()["picture"] as PFFile
userPicture.getDataInBackgroundWithBlock { (imageData:NSData, error:NSError) -> Void in
if (error == nil) {
self.dpImage.image = UIImage(data:imageData)
}
}
但我收到错误:
有用的Apple修补程序提示建议as!改变所以我添加!,但后来我得到错误:
The 'helpful' Apple fix-it tip suggests the "as!" change so I add in the !, but then I get the error:
使用'getDataInBackgroundWithBlock'部分,我也得到错误:
With the 'getDataInBackgroundWithBlock' section, I also get the error:
有人可以解释如何从Parse正确检索照片并使用 Swift 1.2
Can someone please explain how to correctly retrieve a photo from Parse and display it in a UIImageView using Swift 1.2?
推荐答案
PFUser.currentUser()
返回可选类型( Self?
)。所以你应该通过下标来解包返回值。
PFUser.currentUser()
returns optional type (Self?
). So you should unwrap return value to access element by subscript.
PFUser.currentUser()?["picture"]
下标得到的值也是可选类型。因此,您应该使用可选绑定来转换值,因为类型转换可能会失败。
And the value got by subscript is also optional type. So you should use optional binding to cast the value because type casting may fail.
if let userPicture = PFUser.currentUser()?["picture"] as? PFFile {
结果块的参数getDataInBackgroundWithBlock()
方法都是可选类型( NSData?
和 NSError?
)。所以你应该为参数指定可选类型,而不是 NSData
和 NSError
。
And parameters of the result block of getDataInBackgroundWithBlock()
method are both optional type (NSData?
and NSError?
). So you should specify optional type for the parameters, instead NSData
and NSError
.
userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
修改上述所有问题的代码如下:
The code modified the all above problems is below:
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)
}
}
}
这篇关于iOS - 从UIImageView中的Parse检索并显示图像(Swift 1.2错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!