1

我是 Swift 的新手。我的问题是我不确定如何解开可选值。当我打印 object.objectForKey("profile_picture") 时,我可以看到Optional(<PFFile: 0x7fb3fd8344d0>).

    let userQuery = PFUser.query()
    //first_name is unique in Parse. So, I expect there is only 1 object I can find.
    userQuery?.whereKey("first_name", equalTo: currentUser)
    userQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
        if error != nil {
        }
        for object in objects! {
            if object.objectForKey("profile_picture") != nil {
                print(object.objectForKey("profile_picture"))
                self.userProfilePicture.image = UIImage(data: object.objectForKey("profile_pricture")! as! NSData)
            }
        }
    })
4

1 回答 1

1

您将if let用于执行“可选绑定”,仅在没有问题的结果时才执行块nil(并将变量绑定profilePicture到进程中的未包装值)。

它会是这样的:

userQuery?.findObjectsInBackgroundWithBlock { objects, error in
    guard error == nil && objects != nil else {
        print(error)
        return
    }
    for object in objects! {
        if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
            print(profilePicture)
            do {
                let data = try profilePicture.getData()
                self.userProfilePicture.image = UIImage(data: data)
            } catch let imageDataError {
                print(imageDataError)
            }
        }
    }
}

或者,如果您想异步获取数据,也许:

userQuery?.findObjectsInBackgroundWithBlock { objects, error in
    guard error == nil && objects != nil else {
        print(error)
        return
    }
    for object in objects! {
        if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
            profilePicture.getDataInBackgroundWithBlock { data, error in
                guard data != nil && error == nil else {
                    print(error)
                    return
                }
                self.userProfilePicture.image = UIImage(data: data!)
            }
        }
    }
}

这将是一些类似的东西,if let用来解开那个可选的。然后您必须获取与该对象NSData相关联的PFFile对象(可能来自getData方法或getDataInBackgroundWithBlock)。

请参阅The Swift Programming Language中的可选绑定讨论。

于 2016-01-25T00:03:47.933 回答