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)")
}
}
}
Related
new programmer trying to learn Swift and I'm trying to set my app up to only show the current users post on a parse photosharing database. The first method here in theory should add the current user to the "followingWho" array.
override func viewDidLoad() {
super.viewDidLoad()
let userQuery = PFUser.query()
userQuery?.whereKey("username", equalTo: PFUser.currentUser()!.username!)
userQuery?.findObjectsInBackgroundWithBlock ({
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
//no error
if let objects = objects {
for object in objects {
let followingWho = object["followingWho"] as! NSArray!
self.loadData(followingWho)
}
}
} else {
//error
NSLog("Error")
}
})
self.tableView.reloadData()
}
then my second method here should display the posts and filter out all but the current users
func loadData(followingWho: NSArray) {
let query = PFQuery(className: "Posts")
query.whereKey("addedBy", containedIn: followingWho as! [PFObject])
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil) {
//No error
//let posts = posts as! [PFObject]
if let posts = posts {
for post in posts {
self.images.append(post["Image"] as! PFFile)
self.imageCaptions.append(post["Caption"] as! String)
self.imageDates.append(post["date"] as! String)
self.imageUsers.append(post["addedby"] as! String)
}
self.tableView.reloadData()
}
} else {
//error
NSLog("Error")
}
}
}
But nothing seems to be working. The code compiles and runs but it seems to only pull up a blank screen loading none of the posts.
This could be the problem, although if it is not the problem, it is certainly a problem: you are trying to update the UI from a background thread. findObjectsInBackgroundWithBlock calls its completion block in the background, and updating UI from the background is a big no-no. Instead, call your UI updates on the main thread:
dispatch_async(dispatch_get_main_queue(), {
//Do your UI updates here
})
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 {
My Question is very simple,
I'm Learning iOS development and I'm stuck with tableviewcontroller
I can add Values to tableview with array, but when I try to append value from Parse, it's not working.
Here is the code:
var names: [String] = ["Name_one", "Name_two"]
let query: PFQuery! = PFUser.query()
override func viewDidLoad() {
super.viewDidLoad()
query.whereKey("objectId", notEqualTo: PFUser.currentUser()!.objectId!)
query.findObjectsInBackgroundWithBlock { objects, error in
if (error == nil) {
for user: PFUser in (objects as! [PFUser]) {
self.names.append(user.username as! String)
}
} else {
print("Error")
}
}
Screen Shot Attachment
You must to reload your tableview after get data finished
Code:
query.findObjectsInBackgroundWithBlock { objects, error in
if (error == nil) {
for user: PFUser in (objects as! [PFUser]) {
self.names.append(user.username as! String)
}
yourTableview.reloadData()
} else {
print("Error")
}
}
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
I am retrieving data in data. This is my code..
var data:NSMutableArray = NSMutableArray()
func loadData() {
data.removeAllObjects()
var findData:PFQuery = PFQuery(className: "Sweets")
findData.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error != nil {
println(error)
} else if let objects = objects {
for object in objects {
self.data.addObject(object)
}
var array:NSArray = self.data.reverseObjectEnumerator().allObjects
self.data = array as! NSMutableArray // Getting error here.. Could not cast value of type '__NSArrayI' (0x10391c420) to 'NSMutableArray' (0x10391c4e8).
self.tableView.reloadData()
}
}
}
please somebody help me.. i m stuck here and i am beginner .
Do casting in proper way like as follows :
var findData:PFQuery = PFQuery(className: "Sweets")
findData.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error != nil {
println(error)
} else if let objects = objects {
for object in objects {
self.data.addObject(object)
}
var array:NSMutableArray = NSMutableArray(array: self.data.reverseObjectEnumerator().allObjects)
self.data = array as NSMutableArray
self.tableView.reloadData()
}
}