Extra argument in Call for Parse in Swift - swift

All I am trying to get multiple objects out of a parse database.
Here is some of my code :
So this does the query :
var MainPicture = PFQuery(className: "Staff")
MainPicture.whereKey("Position", equalTo: "Sales Manager")
MainPicture.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
self.getMainImageData(objects as [PFObject])
}
else{
println("Error in retrieving \(error)")
}
Then I want to get a few rows out of the query :
func getMainImageData(objects: [PFObject]) {
for object in objects {
let MainPic = object["StaffPic"] as PFFile
let MainData = object["FirstName","SecondName","Position"] as PFFile
MainPic let works, but when I try and do multiple ones like MainData , I get an error : "Extra argument in call" .. I thought this would have worked.

I suspect you cannot subscript PFObject with multiple items. It is like calling
dictionary["key1", "key2"]
That will also result in too many arguments.
It is confusing that your variables are Capitalized. They look like class names.

Related

Is it possible to create an Array of specific Objects in Parse?

I have made a QR scanner App, I have manually put some QR codes into parse for it to recognise, any QR codes scanned that I haven't put into parse don't get recognised.
The only thing to tell them apart is their (Info) i.e "restaurant", "nail salon" etc.
I am after a way to be able to record an Integer of how many times the chosen QRCode has been scanned, to then place on a label in the app.
I can (.count) ALL of the qrCodes saved and scanned by the user but can't seem to figure out how I can then either put all "Nail Salons" into their own array on parse or run a For loop matching the ones I need.
// The code below will retrieve everything in the "info" column and print it to console
// This prints "Nails Salon" x 5, "Restaurant" x3 and "Coffee Shop" x 7 in the order that they were scanned (Unorganised)
// What block of code could I make to display what PFuser.current currently has in their parse?
// E.g. PFUser has scanned "Nail Salon" 5 Times, "Restaurant" 3 time etc etc
let infoCheck = PFQuery(className: "UserQRCodes")
infoCheck.whereKey("info", contains: "")
infoCheck.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if let error = error {
print(error.localizedDescription)
} else if let objects = objects {
print(objects)
}
}
// To retrieve everything the USER has scanned and display it as String on the APP
let query = PFQuery(className: "UserQRCodes")
query.whereKey("userName", equalTo: PFUser.current()!)
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if let error = error {
//log details of the failure
print(error.localizedDescription)
} else if let objects = objects {
let stampees: Int = objects.count
let totalStampees = String(stampees)
self.stampeesCollectedLabel.text = totalStampees
print(objects.count)
}
}
// Do any additional setup after loading the view.
}
You want to filter elements in your array of scans. For each code type, call something like
// '$0' is your PFObject. Replace 'name' with whatever `PFObject` property
// represents the object's type
let nailSalons = objects.filter { $0.name == "Nail Salon" }
You can then use this filtered array to get your count.
Note that the filter { $0... } syntax is a shorthand for
objects.filter { (object) throws -> Bool) in
return object.name == "Nail Salon"
}
You'll need to use the full version if your condition is anything more complicated than a simple one-line expression. Note that in the short version, the return is implied.

What am I doing wrong downloading data from parse?

I am trying to download some data from parse but I get an error message saying "Value of type 'PFObject' has no member 'name' What am I doing wrong?
here is my parse dashboard screenshot
here is my code to upload the data to parse:
var coordinates = PFGeoPoint (latitude: (newCoordinate2.latitude), longitude:(newCoordinate2.longitude))
var aboutSpot = PFObject(className: "spotdetail")
aboutSpot ["PFGeoPoint"] = coordinates
aboutSpot["name"] = "name"
aboutSpot.saveInBackgroundWithBlock { (succes, error) -> Void in
print("separate name and geopoint have been saved")
}
and here is my code to download my data:
var query = PFObject.query()
query!.findObjectsInBackgroundWithBlock ({ (objects, error) in
if let places1 = objects {
for object in places1 {
if let spotdetail = object as? PFObject {
self.rideSpots.append(spotdetail.name!)
}
}
}
print(self.rideSpots)
})
also not that on the line that says
if let spotdetail = object as? PFObject {
I get a warning saying "conditional cast from 'PFObject' to 'PFObject' always succeeds
I can probably solve this pretty easily but I wanted to mention it in case it could help solve the issue

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)

Cannot Subscript A PFObject Error

I've attempted to solve this error, but I've had no luck in doing so. I'm getting the error: Cannot subscript a value of type '[PFObject]' with an index of type 'String' On this line of code: self.postDates.append(posts["createdAt"] as! String).
This is the portion of code I'm having trouble with:
var posts : [Post] = []
var postDates = [String]()
func loadData() {
var query = PFQuery(className: "Post")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {(posts: [PFObject]?, error: NSError?)-> Void in
if error == nil {
if let posts = posts {
for post in posts {
self.postDates.append(posts["createdAt"] as! String)
}
self.tableView.reloadData()
}
} else {
// is an error
}
}
}
I'm trying to get the date and then display it every time the user create a new post utilizing Parse. Can anyone explain what is going on?
This is the tutorial I'm following along with: https://www.youtube.com/watch?v=L3VQ0TE_fjU
Because posts is an array of PFObject, how can you get an element inside from String? It's supposed to be an Int. It's just your typo, you already knew what you are doing. post is the PFObject you want.
for post in posts {
self.postDates.append(post["createdAt"] as! String)
}
You are trying to get (and add) the created at date of the PFObject,
instead you are getting the date of and array of PFObject (Which Posts is).
You should try to get the elements in the array, and get the date from the element instead of the array.
for post in posts{
postDates.append(post["createdAt"] as! String)
}

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