This is my initialisation of the array:
var restaurantsArray = [String]()
Here is the query function:
func loadRestaurants(){
let fetchRestaurantsQuery = PFQuery(className: "Restaurants")
fetchRestaurantsQuery.findObjectsInBackgroundWithBlock{ (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil{
//after successfull fetch
print("b")
if let fetchedRestaurants = objects{
print("c")
for fetchedRestaurant in fetchedRestaurants{
print("a")
self.restaurantsArray.append(fetchedRestaurant.objectForKey("Name") as! String)
print(fetchedRestaurant.objectForKey("Name") as! String)
}
}
}else{
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
For some reason, the code in the for-loop is never called. Any suggestions to fix this?
Since objects is declared as optional [PFObject]? the proper optional binding syntax is just
if let fetchedRestaurants = objects {
and fetchedRestaurant in fetchedRestaurant is pretty weird.
for fetchedRestaurant in fetchedRestaurants {
Related
How can I query after a specific row where the objectId is equal to a objectId I have stored?
This is my query code:
func queryStory(){
let query = PFQuery(className: "myClassStory")
query.whereKey("isPending", equalTo: false)
query.limit = 1000
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
for post in posts! {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
print("Done!")
}
else{
print(error)
}
}
}
This is my Parse database class:
What I want, is to only query the items that was createdAt after the objectId: woaVSFn89t. How can I do this?
Try filtering the objects once you have found them:
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil){
// Success fetching objects
var thePostTime = NSDate()
for post in posts! {
if post.objectId == "The Object Id You Were Trying To Find" {
thePostTime = post.createdAt!
}
}
for post in posts! {
if post.createdAt!.isGreaterThan(thePostTime) == true {
if let imagefile = post["userFile"] as? PFFile {
self.userFile.append(post["userFile"] as! PFFile)
self.objID.append(post.objectId!)
self.createdAt.append(post.createdAt!)
}
}
}
print("Done!")
}
else{
print(error)
}
}
You will notice that I compared the dates using this: NSDate Comparison using Swift
Before the for-loop make a variable:
var havePassedObjectId = false
Then inside the for-loop check if the current post is equal to the object id you want:
if post.objectid == "woaVSFn89t" {
self.userFile.append(post["userFile"] as! PFFile)
//Continue appending to arrays where needed
havePassedObjectId = true
} else if havePassedObjectId == true {
self.userFile.append(post["userFile"] as! PFFile)
//Continue appending to arrays where needed
}
This will check if you have already passed the object and append all the objects after.
I am trying to build a chat application, but I have a problem with this code:
func loadData() {
let FindTimeLineData: PFQuery = PFQuery(className: "Message")
FindTimeLineData.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, NSError) -> Void in
self.MessagesArray = [String]()
for MessageObject in objects {
let messageText: String? = (MessageObject as! PFObject) ["Text"] as? String
if messageText != nil {
self.MessagesArray.append(messageText!)
}
}
}
}
I need to retrieve data from Parse, but the .findObjectsInBackgroundWithBlock method tells me that it cannot convert a value of type AnyObject into Void in. How can I resolve this problem? Thanks in advance.
Try it like this instead:
var query = PFQuery(className: "Message")
query.findObjectsInBackgroundWithBlock {
(remoteObjects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
print("Retrieved \(remoteObjects!.count) messages from server.")
self.MessagesArray = [String]() // By convention, you should name this "messagesArray" instead, and initialize it outside this method
for messageObject in remoteObjects {
if let messageText: String? = messageObject["Text"] as? String {
self.messagesArray.append(messageText)
}
}
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
(not properly proof-read, but you should be able to get it to work from this)
For the record, there are LOTS of duplicate questions with this problem - i know, as I had the same problem after converting Parse code to Swift 2.1.
So, please do a little more research before you post a question. Often, SO even hints at you similar questions as you are typing...
As for the answer, the Parse API doesn't force you to cast the object as AnyObject anymore in the completion block of a query, so it can look just like this:
query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let messages = objects {
for message in messages {
.... etc
I am saving a parse query to a array but i ket the following error on if let objects = objects as? [PFObject]
And the following error happens Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals.
any one know how to solve this?
func getArray(funcstring: String){
var userGeoPoint: PFGeoPoint
PFGeoPoint.geoPointForCurrentLocationInBackground {
(geoPoint: PFGeoPoint?, error: NSError?) -> Void in
if error == nil {
userGeoPoint = geoPoint!
}
}
var searchQuery: [String] = [String]()
var query = PFQuery(className:"User")
query.whereKey("geoLocation", nearGeoPoint:userGeoPoint)
query.limit = 100
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
} else {
print("\(error?.userInfo)")
}
}
}
objects is declared as [PFObject]?.
You're going to downcast the object to something the compiler already knows.
Just check for nil
if let unwrappedObjects = objects {
for object in unwrappedObjects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
or still "swiftier"
if let unwrappedObjects = objects {
self.searchQuery = unwrappedObjects.map{ $0["objectId"] as! String }
}
I'm trying to fetch data from parse and present it in a table view. I'm not able to compile the code as there's an error.
Here's my code:
import UIKit
import Parse
class EventsTableViewController: UITableViewController {
// Array to store event timeline objects from parse
var eventtimelineData:NSMutableArray = NSMutableArray()
override func viewDidAppear(animated: Bool) {
self.loadData()
}
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func loadData(){
// first remove the contents from the array
eventtimelineData.removeAllObjects()
var findTimelineData:PFQuery = PFQuery(className: "Events")
findTimelineData.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]!, error: NSError!) -> Void in
// if query doesn't return any error
if !error{
for object:PFObject! in objects{
self.timelineData.addObject(object)
}
let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects
self.timelineData = array as NSMutableArray
self.tableView.reloadData()
}
}
}
This is the error that am getting:
([AnyObject]!, NSError!) -> Void' is not convertible to 'PFArrayResultBlock?
Could you please help me figure this out? Thanks.
Figured it out. Parse updated their query syntax. This works.
#IBAction func loadData(){
// first remove the contents from the array
eventtimelineData.removeAllObjects()
let query = PFQuery(className:"Events")
query.whereKey("CreatedBy", equalTo:PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock {
(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 as? [PFObject] {
for object in objects {
self.eventtimelineData.addObject(object)
print(object.objectId)
print(object.description)
}
let array:NSArray = self.eventtimelineData.reverseObjectEnumerator().allObjects
self.eventtimelineData = array.mutableCopy() as! NSMutableArray
self.tableView.reloadData()
}
} else {
// Log details of the failure
print("Done")
print("Error: \(error!) \(error!.userInfo)")
}
}
}
I'm doing some iOS app on Xcode 6.4 where I'm using Parse as a back-end, and everything is going fine until I try to add the Parse gotten messages from objects to an staring array.
The error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The thing is I do not know what nil is it talking about as I have unwrapped all the values or at least I think so, help??
Code:
var mensajes:[String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
println("\(PFUser.currentUser()!.username!)")
menuLabel.text = "Bienvenido \(PFUser.currentUser()!.username!)"
/*
var query = PFQuery(className: "Alumnos")
query.whereKey("nombre", hasSuffix: "1")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No error")
println("we have \(objects!.count)")
if let object = objects as? [PFObject] {
for obj in object {
println("\(obj.objectId) ----")
println(obj)
println(obj["nombre"] as! String + "*****")
}
}
} else {
println("a misterious error has appeared \(error!) \(error!.description)")
}
} */
var avisosQuery = PFQuery(className: "Alumnos")
if let papa = PFUser.currentUser() {
avisosQuery.whereKey("userId", equalTo: papa)
avisosQuery.findObjectsInBackgroundWithBlock {
(alumnos: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No Error we have \(alumnos?.count) students")
var grupos: PFObject? = nil
if let obj = alumnos as? [PFObject] {
for alum in obj {
println(alum["nombre"])
//println(alum["grupoId"])
//println(alum)
grupos = alum["grupoId"] as? PFObject
println(grupos!)
var secondQuery = PFQuery(className: "Avisos")
secondQuery.whereKey("grupoId", equalTo: grupos!)
secondQuery.findObjectsInBackgroundWithBlock {
(avisos: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("No error we are home free \(avisos?.count)")
if avisos?.count > 0 {
if let avisoArray = avisos as? [PFObject] {
for av in avisoArray {
println(av["texto"]!)
if let msg: AnyObject = av["texto"] {
println(msg)
self.mensajes.append(msg as! String)
}
}
}
}
} else {
println("something got busted, mate")
}
}
}
}
} else {
println("we screw something up")
}
}
}
}
And I'm in the learning stage with Parse, that why this is in the viewDidLoad() I'm just trying some things.
if let papa = PFUser.currentUser()
The problem is in that line we are not get the userid so technically you are looking for a null value
Right Code :
let papa = PFUser.currentUser().objectId
Try it