iOS How to fetch data for each user parse Swift - ios

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

Related

For loop not being called in query function

I am calling the following function in the viewDidLoad of my collection view controller. I am trying to retrieve a value from the User class of my parse server. My problem is that the for loop is not being called which is not allowing the string value to be retrieved from the column and stored in the array.
func loaduuid(){
let query = PFQuery(className: "_User")
query.whereKey("uuid", equalTo: guestname.last!)
query.findObjectsInBackgroundWithBlock ({ (objects:[PFObject]?, error:NSError?) -> Void in
if error == nil {
print("no error")
for object in objects!{
// add found data to arrays
self.newuuid.append(object.valueForKey("uuid") as! String)
print("uuid added")
}
}
else {
print(error?.localizedDescription)
}
})
}
Why is my for loop not being called and how can I fix this?
You should try to print(objects!.count) to see if the array of PFObjects is empty, that might be why is not iterating through the array. If it prints 0, it means that your query is not finding any results on the server.
If the user is logged in you have every information of his row from _User class in local device, you can access it with
let uuid = PFUser.currentUser()!["uuid"] as! String
or if there are some updated values in _User row you can use
PFUser.currentUser()?.fetchInBackgroundWithBlock...

Issue Reloading Table View After Adding Parse Object

I have a UITableViewController that displays data from a Parse query. It get the data and displays it fine except when I create a new object and run the query again to get the new data. When I create a new object the table view keeps the existing data in my array and displays it but it appends all the data from the query to the array so the objects that already existed prior to creating the new object get displayed twice. I tried emptying the arrays at the start of the query function but since I have the skip property set on the query I can't do that because my array will only get everything after the skip if the limit is reached. So, how can I just add the new object to my array?
I should also mention that I can't simply add the new object name to the array in addCollection() because I have to add the objectId to my objectID array.
func getCollections() {
activityIndicator?.startAnimating()
// collections = [] - Can't do this because of the skip (if the skip is used)
// objectID = []
let query = PFQuery(className: "Collections")
query.whereKey("user", equalTo: PFUser.currentUser()!)
query.orderByAscending("collectionName")
query.limit = limit
query.skip = skip
query.findObjectsInBackgroundWithBlock( {
(objects, error) -> Void in
if error == nil {
if let objects = objects as [PFObject]! {
for object in objects {
let collectionName = object["collectionName"] as! String
let id = object.objectId
self.collections.append(collectionName)
self.objectID.append(id!)
}
}
if objects!.count == self.limit {
self.skip += self.limit
self.getCollections()
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.activityIndicator!.stopAnimating()
}
} else {
var errorString = String()
if let message = error!.userInfo["error"] {
errorString = message as! String
}
print(errorString)
}
})
}
func addCollection(name: String) {
let collection = PFObject(className: "Collections")
collection["user"] = PFUser.currentUser()
collection["collectionName"] = name
collection.saveInBackground()
getCollections()
}
This code is logically flawed and can be simplified:
func addCollection(name: String) {
let collection = PFObject(className: "Collections")
collection["user"] = PFUser.currentUser()
collection["collectionName"] = name
collection.saveInBackground()
getCollections()
}
problems include:
your save runs in the background and isn't complete before you try to reload
your reload doesn't update or reset the skip and limit values
Unless you need to check for updates from other users then you shouldn't make a new request to the server to get new details. Instead you should add a completion block on the save and in there:
get the name and id and add those values to your data source arrays
update the skip value by adding one

Make a Query with a Pointer in Parse and Swift

I'm trying to make a Query with a Pointer in Parse.
Basically I have two classes "commentsTable" and "_User", I want to get the comment of the user from class "commentsTable" on a determined post, and then get the username and the profile_pic from the class "_User"
_User Class
commentsTable Class
func loadAndShowComments(){
let query2 = PFQuery(className: "commentsTable")
query2.orderByDescending("createdAt")
query2.whereKey("newsColumns", equalTo: printteste!)
query2.includeKey("username")
query2.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if let objects = objects as [PFObject]? {
for object in objects {
print(object["commentColumn"])
}
}
for cardset in objects! {
var lesson = cardset["username"] as! PFObject
var name = lesson["username"] as! String
print("By user: \(name)")
}
I'm able to see the query, I print the result an I have the following output:
This is a post!
This is a test post!
By user: teste#teste.com
By user: mmachado
And in my app I display this informations inside a TableView, I'm successfully can show the results for the Query in the func cellForRowAtIndexPath:
if let usuarioComentario = object?["commentColumn"] as? String {
cell?.usuarioComentario?.text = usuarioComentario
}
But I'm no able to return the values of my other class, _User
I think I misunderstood some concept but at this point I don't know what concept, any ideas?
Thanks.
By using query2.includeKey("username") you are already retrieving all of the User data associated with each commentsTable object.
You can access the related User data using the following.
if let commentUser = object["username"] as? PFUser {
let name = commentUser["username"] as! String
let profilePicture = commentUser["profile_pic"] as! PFFile
}
You need to store the query results to an array for later use if you aren't already. If you are using Parse's provided PFQueryTableViewController this will be handled for you by implementing the queryForTable() method and the results are automatically stored in an array of dictionaries called objects.
It is also worth noting that you will have to still have to load the PFFile because they are not included in query results. You will want to assign the PFFile to a PFImageView and then call loadInBackground. See the example below.
let imageView = PFImageView()
// Set placeholder image
imageView.image = UIImage(named: "placeholder")
// Set remote image
imageView.file = profilePicture
// Once the download completes, the remote image will be displayed
imageView.loadInBackground { (image: UIImage?, error: NSError?) -> Void in
if (error != nil) {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
} else {
println("image loaded")
}
}
Lastly, I'd recommend changing the name of the User pointer within commentsTable from "username" to "user" so there is no confusion with the username field of the user class. Here's a link to a great tutorial which you may also find helpful

Retrieve the userInfo using Pointer. Parse

I have a class called Posts in which i've postedBy column where i am saving the PFUser.currentUser() (pointer). so i want to retrieve the username, profile picture and stuff from the _User class using postedBy in the Posts class. What is the shortest and efficient way to achieve this? i am not much familiar with relation queries.
I believe that instead of saving the user pointer, you should save the user's username then it comes easier for you to retrieve everything.
var query = PFQuery(className:"Posts")
var username = PFUser.currentUser()?.username
query.whereKey("username", equalTo: username!)
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
if let objects = objects as? [PFObject]
{
for one in objects {
var pictureImage = one["theFile"] as! PFFile
pictureImage.getDataInBackgroundWithBlock({ (dataToget:NSData?, error:NSError?) -> Void in
if error == nil {
if let Image = UIImage(data: dataToget!){
// then you have the image
// save the image to array
// reload the tableview
}
}
})
}
}
}
}

findObjectInBackgroundWithBlock nested ios

I am developing app using ios, swift and parse.com as backend.
My problem is I need one query object result in second query object like below code. but when i use below code GUI become unresponsive for some time because of findObjects() method. I have used findObjectsInBackgroundWithBlock() instead but than tableview self.posts display only one record in tableview. I have 10 record in post table.
Can you guide me proper way how to resolve below issue.Actually I does not want to use findObjects() method.
var query = PFQuery(className:"Post")
var fquery = PFQuery(className: "Friends")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
let user = PFUser.currentUser()
if let objects = objects as? [PFObject] {
for object in objects {
friendArray.removeAll(keepCapacity: false)
fquery.whereKey("whosefriend", equalTo: object["postusername"])
var fobjects = fquery.findObjects()
for fobject in fobjects {
friendArray.append(fobject["friendname"] as String)
}
if (contains(friendArray, user["fullname"] as String)) {
let post = Post(.......)
self.posts.append(post)
}
}
}
self.tableView.reloadData()
} else {
println("Error: \(error) \(error.userInfo!)")
}
}
One option is to make your "postusername" a pointer column in class Post that points to Friends class and then you would only need one query that would go something like:
var query = PFQuery(className:"Post")
query.includeKey("postusername") //this would include the object that it points to i.e. the Friends object you saved there
... then in your for loop ...
for object in objects! {
let friend = object["postusername"] // now friend is the Friends object
let friendName:String = friend["friendname"] as? String
friendArray.append(friendName)
}
Note: this requires you saving "postusername" as a PFObject of Class Friends. Parse iOS docs explain this well.
https://parse.com/docs/ios/guide
I have resolve the issue by using relational query.
var query = PFQuery(classWithName: "Post")
var fQuery = PFQuery(className:"Friends")
fQuery.whereKey("friendname", equalTo: cuser["fullname"])
query.whereKey("postusername", matchesKey:"whosefriend", inQuery:fQuery)

Resources