我想当一个按钮被点击时,一个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)
})
}
非常感谢您的阅读。请帮帮我!!
如果我理解正确的话,你应该这样做:
friendsRelation.addObject(object);
其中object
为您之前查询的PFUser
。