Unable to retrieve createdAt values from Parse objects - ios

I cannot get the createdAt value from Parse for each object.And I dont want to have to save an additional timestamp as a String when the data is sitting right there.
This is the list of what i was doing.I hope someone who can help
----------------------------------------------------------------------
var followArray = [String]()
var resultsNameArray = [String]()
var resultsIcon = [PFFile]()
var resultsImgArray = [PFFile?]()
var resultsTimeTampArray = [NSDate?]()
-------------------------------------------------------------------
func refreshResult()
{
var followQuery = PFQuery(className: "Follow")
followQuery.whereKey("user", equalTo: PFUser.currentUser()!.username!)
followQuery.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil
{
for object in objects!
{ self.followArray.append(object.objectForKey("Following") as! String)
}
var query = PFQuery(className: "Moments")
query.whereKey("userName", containedIn: self.followArray)
query.addDescendingOrder("createdAt")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil
{
for object in objects!
{
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resultsIcon.append(object.objectForKey("icon") as! PFFile)
self.resultsImgArray.append(object.objectForKey("image") as? PFFile)
//tried to use "createdAt" property but it i still getting nil value from Parse
self.resultsTimeTampArray.append(object.objectForKey("createdAt") as! NSDate)
}
//reload table
self.resultsTable.reloadData()
}
}
}
}
-----------------------------------------------------------------------
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:TimelineCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TimelineCell
enter code here //I'v got an error here!
//fatal error: unexpectedly found nil while unwrapping an Optional value
// dataFormatter
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var strDate = dateFormatter.stringFromDate(self.resultsTimeTampArray[indexPath.row]!)
return cell
}

Don't access it using objectForKey, just access it directly via the createdAt property.
As explicitly stated in the docs, the keys:
This does not include createdAt, updatedAt, authData, or objectId. It does include things like username and ACL.

You can access it directly in your for object loop like this.
object.updatedAt
instead of
objectforkey("updatedAt")

Related

Why is the app crashing when I try to append an array?

I am importing an array from parse, and I want to add that array to an array of arrays, but the app crashes when it tries to append the imported array. Why is that occurring and how can I fix it? Crash error is Thread 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0 I commented the append line and it does not crash, so it has to be that line.
var animalarray: [[String]] = []
let query = PFQuery(className: "animals")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil{
for object in objects!{
if let animalss = object["CoordinateTest"]{
print("coord \(animalss)")
self.animalarray.append(animalss as! [String])//crashes here
}
}
}
}
You should create a method that retrieves the data, and use queries to specify what you want. Also you should create a temporary variable to hold to retrieved data and append that variable to the array.
Ex.)
var animalsArray: [String] = []
func retrieveData(){
let query = PFQuery(className: "animals")
query.whereKey("Key", equalTo: object)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(object:[PFObject]?, error:NSError?) -> Void in
if ( error != nil ){
print(error?.localizedDescription, error?.userInfo)
} else {
for temp: PFObject in object! {
let animals: String = temp["CoordinateTest"] as! String
self.animalsArray.append(animals!)
}
}
}
}

how to retrive data from a user pointer on Parse using swift

On Parse I have users with Facebook profile and Email login profile. So I want to bury for users data in my twitter-like app.
In my "messages" class on Parse I have column "sender" that contains pointers to parse users.
I just want to retrive and show the name of users in class "messages" contained in the column "sender" wich contains pointers to PFUsers of which I need data for keys
"first_name"
"last_name"
"profile_picture"
How can I retrive their data like name and image in order to show them in a tableview?
these are the declarations of my arrays:
var sendersArray : [String] = []
var picturesArray : [NSData] = []
maybe I could use something like this tuple, but I can't understand how to grab data from pointers
for user in list {
let firstName = "fist_name"
let lastName = "last_name"
let oProfileImage = NSData() //"image_profile" as! NSData
otherUsers.append((oName: firstName, oLastName: lastName, oImageProfle: oProfileImage))
}
version - 1:
I started with printing the whole pf object
//******************************************************
func theSearch() {
let theSearchQuery = PFQuery(className: "Messages")
theSearchQuery.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
for object in objects! {
let theName = object.sender!
print(object)
print(theName)
sendersArray.append(theName)
let profilePicture = object["profile_pic"] as! PFFile
picturesArray.append(profilePicture)
}
self.tableView.reloadData()
})
}
//*******************************************************
version - 2:
then, found this solution, but still, doesn't
func theSearch() {
let theSearchQuery = PFQuery(className: "Messages" )
theSearchQuery.includeKey("sender")
theSearchQuery.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
for object in objects! {
let theName = object.sender!["first_name"] as? String
print(object)
print(theName)
sendersArray.append(theName)
let profilePicture = object["profile_pic"] as! PFFile
picturesArray.append(profilePicture)
}
self.tableView.reloadData()
})
}
errors:
seems to be a problem with sender, maybe I shouldn't use it
thanks in advance
let theName = object.objectForKey("sender")!.objectForKey("first_name") as! String
Complete Code:
func theSearch() {
let theSearchQuery = PFQuery(className: "Messages")
theSearchQuery.includeKey("sender")
theSearchQuery.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
for object in objects! {
let theName = object.objectForKey("sender")!.objectForKey("first_name") as! String
print(object)
print(theName)
self.sendersArray.append(theName)
let profilePicture = object["profile_picture"] as! PFFile
self.picturesArray.append(profilePicture)
}
self.tableView.reloadData()
})
}
Also, your picturesArray should be of type PFFile, like this:
var picturesArray = [PFFile]()
NOT NSData. change that at the top of your class.
-----EDIT------:
If you want to retrieve an image from a parse query, do this:
1) at the top of your class, declare the following arrays to store the results:
// your images will be stored in the file array
var fileArray = [PFFile]()
// your first and last names will be stored in String Arrays:
var firstNameArray = [String]()
var lastNameArray = [String]()
2) perform the query:
let query1 = PFQuery(className: "_User")
query1.orderByDescending("createdAt")
query1.findObjectsInBackgroundWithBlock({
(objects : [AnyObject]?, error : NSError?) -> Void in
if error == nil {
for x in objects! {
let firstName = x.objectForKey("first_name") as! String
let lastName = x.objectForKey("last_name") as! String
self.firstNameArray.append(firstName)
self.lastNameArray.append(lastName)
if x.objectForKey("profile_picture") as? PFFile == nil {
print("do nothing cause it's nil")
}
else {
let file:PFFile = x.objectForKey("profile_image") as! PFFile
self.fileArray.append(file)
}
}
self.tableView.reloadData()
}
})
Note I am using Swift 2 and Xcode 7. Syntax is slightly different in Xcode 6.4 and Swift 1.2.

Parse: PFObject is loaded without Attributes

I need to get some 'Kurse' (PFObjects) from the database and then I need to get the name of another PFObject which is a pointer of the 'kurs' but if I try to do this nothing happens. There is no error and the program does not break or something like that but the "test2" is not printed!
let user = PFUser.currentUser()
let query = PFQuery(className: "Kurs")
query.whereKey("stufe", equalTo: user!["stufe"])
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error != nil {
print(error)
}
else if let kurse = objects{
print("kurse:", kurse)
for kurs in kurse{
print("kurs:", kurs)
var gibtEsSchon = false
if gibtEsSchon == false{
print("test1")
let fach = kurs["fach"] as! PFObject
print("fach", fach)
let name = fach["name"] as! String
print("test2")
self.daten.append(Fach(dieKurse: [kurs], name: name))
print("daten 3", self.daten)
}
}
}
So the line
let name = fach["name"] as! String
is not called.
But I think I know why: If I print("fach", fach) the result doesn't have the attribute 'name' that it should have. I think that the PFObject is not loaded completely:
What I get:
fach {
}
What I want:
fach {
name = German;
}
Adding query.includeKey("fach") above query.findObjectsInBackgroundWithBlock should fix that.
From the PFQuery class reference, includeKey will
Make the query include PFObjects that have a reference stored at the provided key.

Query on PFUser according to key value (Swift)

I have PFUser saved as a pointer in this class. I'd like to retrieve the user's first name and corresponding "point value"
My attempt below to append that data to it's cell value, but it is only returning the last retrieved object for that key value.
var innerQuery : PFQuery = PFUser.query()!
innerQuery.whereKeyExists("objectId")
let query = PFQuery(className: "myClass")
query.whereKey("userId", matchesQuery: innerQuery)
query.whereKey("points", greaterThan: 1000)
query.findObjectsInBackgroundWithBlock{ (objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = query.findObjects() as? [PFObject]{
for object in objects {
if let listPoints = object.objectForKey("points") as? Int {
var temp = String(listPoints)
cell.pointStatus.text = temp
}
}
}
}
else{
println(error?.description)
}
}
I retrieve the users first name and profile picture in a separate call. Everything is functional aside from the query for points.
if let pfuser = userProfile["first_name"] as? String{
if let pfimage = userProfile["profile_picture"] as? PFFile{
pfimage.getDataInBackgroundWithBlock({
(result, error) in
cell.userIcon.image = UIImage(data: result!)
cell.userName.text = username
})
}
}
It appears that you are only writing the value of listPoints to one cell in
var temp = String(listPoints)
cell.pointStatus.text = temp
If you want to have multiple point values to be displayed, the cell reference will need to be changed.

Swift Parse - local datastore items not appearing in tableView

This is a followup of my question from yesterday yesterdays post
I have successfully saved and object in the local datastore using parse, and and trying to add that object to an array to store them so i can display the contents in a table view. the query is running fine, but it appears to me that nothing is being appended into the array, so nothing shows in the table view. here's my code.
localData.swift file
import Foundation
struct localData {
var date: String!
var latt: NSNumber!
var lattDelta: NSNumber!
var locality: String!
var longi: NSNumber!
var longiDelta: NSNumber!
var name: String!
var note: String!
}
I then declare this globally:
var arrayToPopulateCells = [localData]()
this is my parse query:
func performQuery() {
let query = PFQuery(className: "ParseLighthouse")
query.fromLocalDatastore()
query.whereKey("User", equalTo: PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) lighthouses.")
// Do something with the found objects
if let light = objects as? [PFObject] {
for object in light {
// println(object.objectId)
// println(object.objectForKey("Name"))
// println(object.objectForKey("Locality"))
var singleData = localData()
singleData.name = object["Name"] as! String
singleData.note = object["Note"] as! String
singleData.date = object["Date"] as! String
singleData.latt = object["Latt"] as! NSNumber
singleData.longi = object["Longi"] as! NSNumber
singleData.lattDelta = object["LattDelta"] as! NSNumber
singleData.longiDelta = object["LongiDelta"] as! NSNumber
singleData.locality = object["Locality"] as! String
self.arrayToPopulateCells.append(singleData)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
}
in my table code:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayToPopulateCells.count
}
and
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// var lighthouse = self.lighthouses[indexPath.row]
var data = self.arrayToPopulateCells[indexPath.row]
//setting the prototype cell to link with the identifier set in attributes earlier.
let cell = tableView.dequeueReusableCellWithIdentifier("locationCell") as! lighthouseCell
let row = indexPath.row
cell.cellName.text = data.name
cell.cellPlace.text = data.locality
// cell.cellCoordinates.text = "\(lighthouse.latt)" + ", " + "\(lighthouse.longi)"
// cell.cellNote.text = lighthouse.note
cell.cellDate.text = "\(data.date)"
return cell
}
so im not sure what i'm doing wrong, but it seems that the query is working but nothing is going into the array. any ideas?
i do want to note that the parse object is created on lets say viewcontroller #2, and the query is run on viewcontroller #1 where the table view is. does this make a difference? should i run the query and try to append right after the object is made on the same controller?
I think your problem is you need to call
self.tableView.reloadData()
outside the for object in light { loop
I think your data is being added to the array ok, its just the table view needs to know when its done.
EDIT***
func performQuery() {
let query = PFQuery(className: "ParseLighthouse")
query.fromLocalDatastore()
query.whereKey("User", equalTo: PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) lighthouses.")
// Do something with the found objects
if let light = objects as? [PFObject] {
for object in light {
var singleData = localData()
singleData.name = object["Name"] as! String
singleData.note = object["Note"] as! String
singleData.date = object["Date"] as! String
singleData.latt = object["Latt"] as! NSNumber
singleData.longi = object["Longi"] as! NSNumber
singleData.lattDelta = object["LattDelta"] as! NSNumber
singleData.longiDelta = object["LongiDelta"] as! NSNumber
singleData.locality = object["Locality"] as! String
self.arrayToPopulateCells.append(singleData)
}
self.tableView.reloadData()
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
}

Resources