【问题标题】:How to use Parse API to search user and add user as PFRelation?如何使用 Parse API 搜索用户并将用户添加为 PFRelation?
【发布时间】:2014-06-26 21:21:41
【问题描述】:

我希望当点击按钮时,会弹出一个 UIAlertView 并为用户提供一个 textField 以键入他想要添加的用户。该过程包括在 Parse.com 上搜索 EXACT 用户名并将用户添加到 currentUser 的 PFRelation。

这是 Swift 中的代码。

@IBAction func addFriend(sender : AnyObject) {

    var currentUser = PFUser.currentUser()

    var alert = UIAlertController(title: "Add Friend", message: "Pleae enter a username.", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Username"
        textField.secureTextEntry = false

        // Add button actions here
        var addBtnAction = UIAlertAction(title: "Add", style: UIAlertActionStyle.Default) {
            UIAlertAction in

            var text : String = textField.text

            println("I want to add the user: \(text)")

            var query = PFUser.query()
            query.whereKey("username", equalTo: text)
            query.getFirstObjectInBackgroundWithBlock {
                (object: PFObject!, error: NSError!) -> Void in
                if !object {
                    NSLog("The getFirstObject request failed.")
                    //add alertView here later

                } else {
                    // The find succeeded.
                    NSLog("Successfully retrieved the object.")
                    //This can find username successfully

                    var friendsRelation : PFRelation = currentUser.relationForKey("friendsRelation")
                    var user : PFUser = text  // <<<<---- This is the line that has problem
// Xcode tells me that I cannot express a String as a PFUser
// How can I add the user that has the exact same username?  

                }
            }
        }

        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
        alert.addAction(addBtnAction)
        self.presentViewController(alert, animated: true, completion: nil)

        })
}

非常感谢您阅读本文。请帮帮我!!

【问题讨论】:

    标签: ios xcode parse-platform swift uialertcontroller


    【解决方案1】:

    如果我正确理解您要执行的操作,您应该执行以下操作:

    friendsRelation.addObject(object);
    

    其中object 是您之前查询的PFUser。

    【讨论】:

    • 谢谢!如何将字符串转换为 PFUser?我不知道!
    • 抱歉,我不清楚您要做什么。 object 已经是 PFUser,根据回调签名...您无法将字符串转换为 PFUser,您可以注册一个新用户,这将在本地和远程创建一个新的PFUser...。希望这会有所帮助...
    • 嗨。我希望当用户输入用户名时,Parse.com 会找到用户并将其 PFRelation 添加给用户。添加PFUser的方法是调用friendsRelation.addObject(user)。但是,我不知道如何找到与在 textField 中输入的字符串具有相同用户名的 PFUser。我知道(用户)必须是 PFUser,但是如何找到与字符串同名的 PFUser?或者我应该问,我如何获得我查询的 PFUser?谢谢!
    • 谢谢!我没有意识到返回的值是对象。现在我的问题解决了。非常感谢!!
    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多