简体   繁体   中英

iOS How to fetch data for each user parse Swift

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?

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.

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)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM