0

How can I fetch data for user which I want. For this I want use text field where I write username, and button which will load all information about user. Now my code load all user from data base:

 let query = PFUser.query()
    query?.findObjectsInBackground(block: { (object, error) in
        for objects in object! {
            let user = objects["username"] as! String
            print(user)

        }

    })

How I can make it for user which I want?

2 Answers 2

2

You could filter the users locally like this:

query?.findObjectsInBackground {(objects, error) in
    let users = objects as? [PFUser]
    for object in (users!.filter { $0.username == something }) {
        // do something
    }
}

But that's a pretty bad idea because your list of users might be huge and this is wildly inefficient. If you're using PFQuery, you might want to add a constraint:

let query = PFUser.query()
query.whereKey("username", equalTo: something)

Now, when you call findObjectsInBackground, you'll only get relevant results.

1

You are getting user list in object at:

query?.findObjectsInBackground(block: { (object, error) in

Put a where clause in for loop, to get a single user by matching your required username as:

    for objects in object! where (objects["username"] as! String) == "Your_Text_Field.text" {
        print(objects)

        let userName = objects["username"] as! String
        print(userName)
    }

If you don't want to match exact name rather you want to get a list of user by searching with entered text, then you can apply filter:

    query?.findObjectsInBackground {(object, error) in
        if let users = object as? [PFUser] {
            let filteredUsers = users.filter { $0.username.contains("Your_Text_Field.text") }
            print(filteredUsers)
        }
    }
2
  • Binary operator '==' cannot be applied to operands of type 'Any!' and 'String'
    – Andrew
    Apr 17, 2018 at 6:50
  • @Andrew, Just cast the objects["username"] to String. I have updated my answer. Apr 17, 2018 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.