iOS - 在 UIImageView 中从 Parse 检索并显示图像(Swift 1.2 错误) [英] iOS - Retrieve and display an image from Parse in UIImageView (Swift 1.2 Error)
问题描述
我之前一直在使用以下代码行从 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)
}
}
但我收到错误:
'任何对象?'不可转换为PFFile";你的意思是使用作为!"强迫情绪低落?
'AnyObject?' is not convertible to 'PFFile'; did you mean to use 'as!' to force downcast?
有用"的 Apple fix-it 提示建议使用as!"更改,所以我添加了!,但随后出现错误:
The 'helpful' Apple fix-it tip suggests the "as!" change so I add in the !, but then I get the error:
'任何对象?'不可转换为PFFile"
'AnyObject?' is not convertible to 'PFFile'
使用 'getDataInBackgroundWithBlock' 部分,我也收到错误:
With the 'getDataInBackgroundWithBlock' section, I also get the error:
无法使用类型为 '((NSData, NSError) -> Void)' 的参数列表调用 'getDataInBackgroundWithBlock'
Cannot invoke 'getDataInBackgroundWithBlock' with an argument list of type '((NSData, NSError) -> Void)'
谁能解释一下如何使用 Swift 1.2 从 Parse 正确检索照片并在 UIImageView 中显示它?
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 错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!