Query PFUser not working

80 views Asked by At

I am using this query to find users, it works but it just shows me the first user. I want it to show me the user with the text of an UITextField. How can I do that ? (I have a textfield and there I type in a name and then it should show the parsed users with the name)

PFQuery *query = [PFUser query];

NSArray *users = [query findObjects];

userQuerys.text = users[0][@"username"];

Thanks very much

1

There are 1 answers

0
Erakk On

This code will fetch you all the PFUsers in which username is equal to the name parameter:

- (void)searchUsersNamed:(NSString *)name withCompletion:(void (^)(NSArray *users))completionBlock {
    PFQuery *query = [PFUser query];
    [query whereKey:@"username" equalTo:name];
    [query findObjectsInBackgroundWithBlock:^(NSArray *users, NSError *error) {
         if (!error) {
             // we found users with that username
             // run the completion block with the users.
             // making sure the completion block exists
             if (completionBlock) {
                 completionBlock(users);
             }
         } else {
             // log details of the failure
             NSLog(@"Error: %@ %@", error, [error description]);
         }
     }];
}

An example, if you need to update the UI with the result, for example, a table:

- (void)someMethod {
    // we will grab a weak reference of self to perform
    // work inside the completion block
    __weak ThisViewController *weakSelf = self; 
    //replace ThisViewController with the correct self class

    [self searchUsersNamed:@"Phillipp" withCompletion:^(NSArray *users) {
        //perform non-UI related logic here.
        //set the found users inside the array used by the
        //tableView datasource. again, just an example.
        weakSelf.users = users;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //pefrorm any UI updates only
            //for example, update a table
            [weakSelf.tableView reloadData];
        }];
    }];
}

A small note: the completionBlock here wont run if there is an error, but it will run even if no users were found, so you gotta treat that (if needed. in this example, it was not needed).

Avoid running non-UI related logic on that mainQueue method, you might lock the Main thread, and that`s bad user experience.