Trouble querying for a user and adding that user as a friendship relation in Parse

69 Views Asked by At

I'm trying to query for users in my Parse database and create a friendship between the current user and the queried user. I've gone through a lot of the Parse documentation and tutorials, but I still can't get it working. I keep getting a warnParseOperationOnMainThread error, and I've tried using Parse's recommended debugging practices for that error, but it breaks on some random line of code from the stack that I don't understand. If you could tell me what's wrong, or have another method of implementing the same functionality, I would really appreciate the help. Thanks! Below is the code for my query that isn't working:

-(void)queryForFriend { NSString *searchedFriendName = self.addFriendTextField.text;

PFQuery *friendQuery = [PFUser query];
[friendQuery whereKey:@"username" equalTo:searchedFriendName];
friendList = [friendQuery findObjects];
if(friendList.count > 0)
{
    PFUser *newFriend = friendList.lastObject;

    PFRelation *friendship = [[PFUser currentUser] objectForKey:@"friendShip"];
    [friendship addObject:newFriend];
    [[PFUser currentUser] saveInBackground];
}

}

1

There are 1 best solutions below

1
On BEST ANSWER

[friendQuery findObjects] is a thread-blocking operation that will block your main thread until the network query has completed. You should use the findObjectsInBackgroundWith... method (I forget whether it is withBlock or withCompletion) - you supply an objective-c block (a closure) that will be executed after the network query has finished, but in the meanwhile your app will continue to operate.

If you haven't already, it would be worthwhile reading through Apples asynchronous programming concepts reference.