Cannot Subscript A PFObject Error - swift

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

Related

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

swift parse query not returning objects in ascending order

My query aims to fetch the objects created by a certain number of users. The following are my codes:
var dates = [NSDate]()
var messages = [String]()
let getUsersQuery = PFQuery(className: "followings")
getUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
let followedUser = object["followedUser"] as! String
let getPostsQuery = PFQuery(className: "posts")
getPostsQuery.whereKey("userId", equalTo: followedUser)
getPostsQuery.orderByDescending("updatedAt")
getPostsQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for post in objects {
self.dates.append(post.createdAt as NSDate!)
self.messages.append(post["message"] as! String)
}
print(self.dates)
self.myTableView.reloadData()
})
}
}
}
})
Here's what come up when I print the dates in the log:
However, the content in my tableview is not in an ascending order. In fact the post created most recently is at the bottom of the tableview. One thing I noticed is that the posts of a particular user seems to be shown together. So all of one user's post would appear at the top of the tableview no matter another user has created the newest post. Any idea what is going wrong? thanks!
What you need is a nested query. The array you are trying to get is an of posts. So your query should be on the post table. (Also, your table should be called post not posts. Table names should always be singular. Each post is called a post not a posts.
let postsQuery = PFQuery(className: "post")
postsQuery.orderByDescending("updatedAt")
let usersQuery = PFQuery(className: "following")
usersQuery.whereKey("follower", equalTo:PFUser.currentUser()!.objectId!)
// this might need to change depending on what the followed user is called in the `followings` table.
postsQuery.whereKey("userId", matchesKey:"followed", inQuery:usersQuery)
getPostsQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for post in objects {
self.dates.append(post.createdAt as NSDate!)
self.messages.append(post["message"] as! String)
}
print(self.dates)
self.myTableView.reloadData()
})
Also, you are saving dates and messages in separate arrays. Create a struct or something that has a date and string and have a single array of Post objects.

Retrieve Data in Parse

I have searched through a number of similar topics but have not found a solution as of yet. I am using Parse social and using the login files.
I get the following error:
"AnyObject?" is not convertible to 'String'
I am very new to Swift & Parse - I believe this is the correct method of retrieving data, so please correct me if I am wrong.
var userObjectID = PFUser.currentUser()!.objectId!
var query = PFQuery(className:"User")
query.getObjectInBackgroundWithId("\(userObjectID)") {
(userInfo: PFObject?, error: NSError?) -> Void in
if error == nil && userInfo != nil {
println(userInfo)
let userScore = userInfo["level"] as! String
} else {
println(error)
}
}
Below is the database on Parse
I think you need to unwrap the PFObject you receive:
let userScore = userInfo!["level"] 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
}
}

Extra argument in Call for Parse in 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.