iOS Swift appending value to array - ios

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

Related

Xcode Parse Query button Delete text and photo from a cell

each cell displays the according comments and photo of the user logged-on. They are loaded with parse.
Now you want to Löschen the button deletes the photo and the comments.
Unfortunately this does not work. Wen I click on the button nothing happens
Unfortunately I understand little of swift and can't get on the solution
The query works, and the app displays the photos and Commons.The query and post code:
override func viewDidLoad() {
super.viewDidLoad()
super.viewDidLoad()
let query = PFQuery(className: "Post")
query.whereKey("username", equalTo: PFUser.current()?.username)
query.findObjectsInBackground(block: { (object, error) in
if let posts = object {
for post in posts{
print(posts)
self.comments.append(post["message"] as! String)
self.imageFile.append(post["imageFile"] as! PFFile)
self.tableView.reloadData()
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
}
And here of the "delete"function code that I have tried:
#IBAction func remove(_ sender: Any) {
print("Entered remove")
let query = PFQuery(className: "Post")
query.whereKey("username", equalTo: PFUser.current()?.username)
query.findObjectsInBackground(block: { (object, error) in
if let posts = object {
print(posts)
for post in posts{
print(posts)
if let message = post["message"] as? String, let image = post["imageFile"] as? PFFile {
print("message and image read", message, image)
if let messageIndex = self.comments.index(of: message), let imageIndex = self.imageFile.index(of:image) {
self.comments.remove(at: messageIndex)
self.imageFile.remove(at: imageIndex)
}
}
self.tableView.reloadData()
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
}
The output:
I don't get an error message and nothing is deleted.
Thank you for your help
You do not have access to your current index where and object ids.
So based on that you can remove easy.
The more easy way to implement the delete function is to have an array of objectId for your messages:
self.ids.append(post.objectId)
And when you want to delete it:
let query = PFQuery(className: "Post")
query.whereKey("objectId", equalTo: self.ids.index(of: indexPath.row))
// Make a query in background to only get the object that you want to delete
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
print("The getFirstObject request failed.")
} else if let object = object {
print("Successfully retrieved the object.")
object.deleteInBackground()
}
}
Having different arrays representing the same object is not really good to do. So a better way to handle you problem is have only one array for your post
When you fetch it you can do something like that:
guard let user = PFUser.current() else { return }
let query = PFQuery(className: "Post")
query.whereKey("username", equalTo: user.username)
query.findObjectsInBackground(block: { (posts, error) in
if let posts = posts {
self.posts = posts
}
})
With this way when you want to delete it in the remove function:
if indexPath.row < self.posts.count {
self.posts[indexPath.row].deleteInBackground()
}

Parse - Query after a specific row

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.

Only show friends posts on Parse

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

Fetching data from parse to Table View Controller

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

iOS and Parse throwing exception: "unexpectedly found nil"

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

Resources