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

时间秒杀一切 提交于 2019-12-18 08:48:24

问题


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)

    }
}

But I get the error:

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

The 'helpful' Apple fix-it tip suggests the "as!" change so I add in the !, but then I get the error:

'AnyObject?' is not convertible to 'PFFile'

With the 'getDataInBackgroundWithBlock' section, I also get the error:

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

Can someone please explain how to correctly retrieve a photo from Parse and display it in a UIImageView using Swift 1.2?


回答1:


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 {

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


来源:https://stackoverflow.com/questions/29729883/ios-retrieve-and-display-an-image-from-parse-in-uiimageview-swift-1-2-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!