How to convert AnyObject to PFObject / PFUser in swift?
I am setting up a PFRelation for a custom variable, and I would like to add text to a textbox as PFRelation. I first ask to determine if the input username exists and I make the returned PFUser object. Then I try to add PFUser to PFRelation and that's where it fails because AnyObject cannot be disabled until PFUser / PFObject. How should I do it?
var userQuery = PFUser.query()
userQuery.whereKey("username", equalTo: newUsername.text)
userQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
for object in objects{
if objects.count > 0 {
var PFRelation = PFUser.currentUser().relationForKey("friends")
var addRelation = object["username"] as PFUser
PFRelation.addObject(addRelation)
PFUser.currentUser().saveInBackgroundWithBlock{
(succeeded: Bool!, error: NSError!) in
if error == nil {
println("newuser added")
}
else {
println(error.userInfo)
}
Thank!!
+3
source to share
1 answer
In my opinion it is not possible to do this because PFObject / PFUser is like an array. Thus, I could not distinguish just an object into an array. I also used getFirstObjectInBackgroundWithBlock () because it returns PFObject instead of AnyObject, but not sure if that made a difference. Below is my working code.
var userQuery = PFUser.query()
userQuery.whereKey("username", equalTo: newUsername.text)
userQuery.getFirstObjectInBackgroundWithBlock{ (object, error) -> Void in
if error == nil {
println(object)
var PFRelation = PFUser.currentUser().relationForKey("friends")
var addRelation = object
if addRelation != nil {
PFRelation.addObject(addRelation)
println("new relation added")
}
PFUser.currentUser().saveInBackgroundWithBlock{
(succeeded: Bool!, error: NSError!) in
if error == nil {
println("newuser saved")
}
else {
println(error.userInfo)
}
}
}
else {
println(error)
}
}
0
source to share