Cannot assign result of Parse PFQuery to instance variable of my controller Class in Swift - swift

I'm trying to assign the value returned from the result of a Parse query to an instance variable of my view controller class called "currentProfile". Although the function retrieves the data from the server okay, it seems like it doesn't assign it to my instance variable.
This is my code :
let query = PFUser.query()
query!.getObjectInBackgroundWithId(self.profileId) {
(profile: PFObject?, error: NSError?) -> Void in
if error == nil && profile != nil {
print(profile)
self.currentProfile = (profile as? PFUser)!
} else {
print(error)
}
}
print(currentProfile)
So when I print profile the first time it prints it correctly, however when I print currentProfile outside the function it actually doesn't print anything.
If you have any idea why this is happening or know how could I fix it, it would be greatly appreciated if you could let me know.
Thanks.

Related

query if the data is found - Parse & Swift 3

I'm trying to develop an app that provide User sign up and within the UI I want to query if the email is exists or not.
The problem is since I change from swift 2 to swift 3 I got these errors
var query = PFObject(className:"User")
query.whereKey("email", equalTo: email)
query.findObjectsInBackground {
(objects, error) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects {
for object in objects {
print(object.objectId)
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
/Users/**************/SignUpSenderViewController.swift:49:9:
Value of type 'PFObject' has no member 'whereKey'
/Users/i*************/SignUpSenderViewController.swift:50:9:
Value of type 'PFObject' has no member 'findObjectsInBackground'
any suggestion to solve this challenge ?
I dont know what documentation you checked but the query has to be done this way...
let query = PFQuery(className:"_User")

How can I access value from pointer inside pointer on query with Parse in swift?

How can I access value from pointer inside pointer on query with Parse in swift?
This has to do with three classes in Parse. One is called Post_Story, on is Post and one is User. When I query for Post_Story i am able to retreive pointer info from a key "Post", but is there any way to access information from a pointer within that pointer? (key "createdBy" to User class)
My code looks like this:
let postQuery = PFQuery(className: "Post_Story")
postQuery.whereKey("story", containedIn: storyObjects)
postQuery.includeKey("post")
postQuery.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error:NSError?) in
if error == nil {
for object in objects! {
if let postL = object["post"] as? PFObject {
if postL["createdBy"] != nil {
//this is where I want to get infor from PFUser, but not all info is sent
print((postL["createdBy"] as! PFUser)) //prints PFUser object without username etc.
}
}
}
}
else {}
}
I hope the question is not too stupid...
You can add postQuery.includeKey("post.createdBy") to include the user object in the createdBy column of post.

Array of Parse Pointers (Swift) - is This Possible

I am working on an app where the user is connected (in) multiple school classes. Since a student will be in more than one class, am I able to set an array of pointers to an individual user or is that not possible (maybe a relation is better)?
Here is my code:
let classPointerQuery = PFQuery(className: "Classes")
classPointerQuery.whereKey("class_name", equalTo: self.classNameTextField.text!)
let classQuery = PFQuery.orQueryWithSubqueries([classPointerQuery])
classQuery.findObjectsInBackgroundWithBlock({ (results: [PFObject]?, error: NSError?) -> Void in
if let objects = results {
for object in objects {
let userInfo = PFUser.currentUser()!
userInfo["my_classes"] = object
userInfo.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error != nil {
spinningActivity.hideAnimated(true)
self.displayAlert("Error", message: error!.localizedDescription)
} else if success {
spinningActivity.hideAnimated(true)
self.dismissViewControllerAnimated(true, completion: nil)
} else {
spinningActivity.hideAnimated(true)
self.displayAlert("Something Went Wrong", message: "Please try again")
}
})
}
}
})
* Note: I also tried changing - userInfo["my_classes"] = object - to - userInfo["my_classes"] = [object] - and got an error, "invalid type for key my_classes, expected *Classes, but got array (Code: 111, Version: 1.12.0)"
What I am doing here is querying for the object of the class that I want - lets say the user wants to add the class "Physics" - the query queries for the "class_name" in the Parse class "Classes" and spits out the object. This object is then set the current user's "my_classes" -> a pointer object. I there a way, when the user wants to add "Calculus" that the pointer object in Parse will have 2 pointers instead of replacing the current pointer?
Thanks in advance for the help!
you cant store Pointers in array, you can store objectID in the array as string and do the query like that.... the general rule is that u use Pointers for 1:many relationships in database and Relations in many:many...
Update 1 - Saving objectID to Array in Parse
PFUser.currentUser()!.addObject(somePFObject.objectID!, forKey: "my_classes")
for queries you will than use containedIn
querySetup.whereKey("class", containedIn: array)

Swift ! does not remove Optional()

Before, I have successfully added a ! to force an unwrap to remove the "Optional()" from a variable. I am unable to do this in data returned from Parse.com
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
println(object[myObject]!)
}
} else {
println("Error: \(error) \(error.userInfo!)")
}
}
In the example above, the entire table from the Parse.com class is returned and printed to the console. However,
Optional(...)
is returned for each line even though I force an unwrap using ! at the end
What am I missing?
(Note: myObject is the name of the Column in the Parse Class database)
MirekE was right. It was a nested Optional(Optional()).
to fix I:
println(object[myObject]!!)
You only have to put "!" at the end of your variable, in print area
self.addressLabel.text = "\(subThoroughfare) \(p.thoroughfare!) \n \(p.subLocality!) \n \(p.subAdministrativeArea!) \n)".

Swift querying Parse all objects in class

I have an app that I need to grab all values in the class. I need to get "players" and "total" from the class "runningTotal". Here is the code I have:
var query = PFQuery(className:"runningTotal")
query.selectKeys(["players", "total"])
query.findObjectsInBackgroundWithBlock
{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil
{
self.test = objects[0]["total"]
}
}
I want to set a variable (test) equal to the result of total. I would also want to do this with players. I don't think the above code is right, as it doesn't work. I obviously don't need any constraints as I want to fetch all of the results from this class. How would I go about solving this?
Thanks for any help in advance!
As long as your query is error free, you'll need to iterate through the objects array. As you iterate through each object, which will be of type AnyObject, you will need to cast the object as a PFObject. Then you will be able to grab the data you require from it.
var query = PFQuery(className:"runningTotal")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil{
for object in objects{
if let data = object as! PFObject{
//Set test to total (assuming self.test is Int)
self.test = data["total"] as! Int
}
}
}else{
//Handle error
}
}