I have pull to refresh functionality in TableView Controller, which lists all usernames and who the current user is following (indicated by a checkmark at the end of each row). Here is my refresh function:
var refresher: UIRefreshControl!
func refresh() {
var query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
self.usernames.removeAll(keepCapacity: true)
self.userids.removeAll(keepCapacity: true)
self.isFollowing.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
if user.objectId! != PFUser.currentUser()?.objectId {
self.usernames.append(user.username!)
self.userids.append(user.objectId!)
var query = PFQuery(className: "followers")
query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
query.whereKey("following", equalTo: user.objectId!)
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
if objects.count > 0
{
self.isFollowing[user.objectId!] = true
}
else
{
self.isFollowing[user.objectId!] = false
}
}
if self.isFollowing.count == self.usernames.count
{
self.tableView.reloadData()
self.refresher.endRefreshing()
}
})
}
}
}
}
})
}
It's called in my viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
//pull to refresh funcationlity
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
}
The problem is that when I delete an item manually from the Parse.com database, and pull to refresh in the list view, it does not update. Here are my tableview functions:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = usernames[indexPath.row]
let followedObjectId = userids[indexPath.row]
if isFollowing[followedObjectId] == true {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
let followedObjectId = userids[indexPath.row]
if isFollowing[followedObjectId] == false {
isFollowing[followedObjectId] = true
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
var following = PFObject(className: "followers")
following["following"] = userids[indexPath.row]
following["follower"] = PFUser.currentUser()?.objectId
following.saveInBackground()
}
else
{
isFollowing[followedObjectId] = false
cell.accessoryType = UITableViewCellAccessoryType.None
var query = PFQuery(className: "followers")
query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
query.whereKey("following", equalTo: userids[indexPath.row])
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
object.deleteInBackground()
print(object)
}
}
})
}
}
Related
In my app users are able to log in/ sign up by creating a username and password or by logging in with Facebook. Parse stores their username and password. It does the same for Facebook, but it stores the users token (I think) instead of the username. I then display the users names in a table view, but the Facebook users show up as a user token like : Afjkd233edJ instead of their user name. I am using Facebook graph api also, it stores the name under name in my class User. I am not able however to get that name to post instead of the token thing. Here is the code I am using in my View controller which handles login and sign up and then bellow that is my table view controller which display the users and who they are following or not following. EDIT: I forgot to to mention that I am using parse server and have migrated it over to Heroku and am using the mongoldb dyno.
VIEWCONTROLLER
import UIKit
import Parse
import ParseFacebookUtilsV4
class ViewController: UIViewController {
var signupActive = true
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var signupButton: UIButton!
#IBOutlet weak var registeredText: UILabel!
#IBOutlet weak var loginButton: UIButton!
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})))
self.presentViewController(alert, animated: true, completion: nil)
}
#IBAction func signUp(sender: AnyObject) {
if username.text == "" || password.text == "" {
displayAlert("Error in form", message: "Please enter a username and password")
} else {
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var errorMessage = "Please try again later"
if signupActive == true {
let user = PFUser()
user.username = username.text
user.password = password.text
user.signUpInBackgroundWithBlock({ (success, error) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error == nil {
// Signup successful
//self.performSegueWithIdentifier("login", sender: self)
let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate
var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
} else {
if let errorString = error!.userInfo["error"] as? String {
errorMessage = errorString
}
self.displayAlert("Failed SignUp", message: errorMessage)
}
})
} else {
PFUser.logInWithUsernameInBackground(username.text!, password: password.text!, block: { (user, error) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if user != nil {
// Logged In!
//self.performSegueWithIdentifier("login", sender: self)
let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate
var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
} else {
if let errorString = error!.userInfo["error"] as? String {
errorMessage = errorString
}
self.displayAlert("Failed Login", message: errorMessage)
}
})
}
}
}
#IBAction func logIn(sender: AnyObject) {
if signupActive == true {
signupButton.setTitle("Log In", forState: UIControlState.Normal)
registeredText.text = "Not registered?"
loginButton.setTitle("Sign Up", forState: UIControlState.Normal)
signupActive = false
} else {
signupButton.setTitle("Sign Up", forState: UIControlState.Normal)
registeredText.text = "Already registered?"
loginButton.setTitle("Login", forState: UIControlState.Normal)
signupActive = true
}
}
#IBAction func faceBookLogIn(sender: AnyObject) {
let permissions = ["public_profile"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions, block: {
(user: PFUser?, error: NSError?) -> Void in
if let error = error {
print(error)
} else {
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, gender"])
graphRequest.startWithCompletionHandler( {
(connection, result, error) -> Void in
if error != nil {
print(error)
} else if let result = result {
PFUser.currentUser()?["name"] = result["name"]!
PFUser.currentUser()?.saveInBackground()
let userId = result["id"]! as! String
}
})
if let user = user {
//self.performSegueWithIdentifier("login", sender: self)
let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate
var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
}
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
if let username = PFUser.currentUser()?.username {
let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate
var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
TABELVIEW
import UIKit
import Parse
class TableViewController: UITableViewController {
var usernames = [""]
var userids = [""]
var isFollowing = ["":false]
var refresher: UIRefreshControl!
func refresh() {
var query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
self.usernames.removeAll(keepCapacity: true)
self.userids.removeAll(keepCapacity: true)
self.isFollowing.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
if user.objectId! != PFUser.currentUser()?.objectId {
self.usernames.append(user.username!)
self.userids.append(user.objectId!)
var query = PFQuery(className: "followers")
query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
query.whereKey("following", equalTo: user.objectId!)
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
if objects.count > 0 {
self.isFollowing[user.objectId!] = true
} else {
self.isFollowing[user.objectId!] = false
}
}
if self.isFollowing.count == self.usernames.count {
self.tableView.reloadData()
self.refresher.endRefreshing()
}
})
}
}
}
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = usernames[indexPath.row]
let followedObjectId = userids[indexPath.row]
if isFollowing[followedObjectId] == true {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
let followedObjectId = userids[indexPath.row]
if isFollowing[followedObjectId] == false {
isFollowing[followedObjectId] = true
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
var following = PFObject(className: "followers")
following["following"] = userids[indexPath.row]
following["follower"] = PFUser.currentUser()?.objectId
following.saveInBackground()
} else {
isFollowing[followedObjectId] = false
cell.accessoryType = UITableViewCellAccessoryType.None
var query = PFQuery(className: "followers")
query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
query.whereKey("following", equalTo: userids[indexPath.row])
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
object.deleteInBackground()
}
}
})
}
}
}
I have a collectionView which is populated with around 60 images downloading from parse. These images can be updated depending if any new ones have been uploaded.
But my problem is after I load the view, and I refresh the data using PullToRefresh function, the collection view Flashes white and then displays the images again...
here's a video to show you :
https://www.youtube.com/watch?v=qizaAbUnzYQ&feature=youtu.be
I have been trying to fix this all day & find a solution, but I have had no success..!
Heres how I'm querying the images :
func loadPosts() {
self.activityView.startAnimating()
let followQuery = PFQuery(className: "Follows")
followQuery.whereKey("follower", equalTo: PFUser.currentUser()!.username!)
followQuery.findObjectsInBackgroundWithBlock ({ (objects:[PFObject]?, error:NSError?) -> Void in
if error == nil {
self.followArray.removeAll(keepCapacity: false)
for object in objects! {
self.followArray.append(object.valueForKey("following") as! String)
}
let query = PFQuery(className: "Posts")
query.limit = self.page
query.whereKey("username", notContainedIn: self.followArray)
query.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query.findObjectsInBackgroundWithBlock ({ (objects:[PFObject]?, error:NSError?) -> Void in
if error == nil {
self.postImage.removeAll(keepCapacity: false)
self.uuidArray.removeAll(keepCapacity: false)
self.usernameArray.removeAll(keepCapacity: false)
for object in objects! {
self.postImage.append(object.valueForKey("image") as! PFFile)
self.uuidArray.append(object.valueForKey("uuid") as! String)
self.usernameArray.append(object.valueForKey("username") as! String)
}
} else {
print(error!.localizedDescription)
}
self.collectionView.reloadData()
self.refresher.endRefreshing()
self.activityView.stopAnimating()
self.boxView.removeFromSuperview()
})
}
})
}
And here is how I am pulling to refresh:
override func viewDidLoad() {
super.viewDidLoad()
refresher.addTarget(self, action: "reload", forControlEvents: UIControlEvents.ValueChanged)
collectionView.addSubview(refresher)
loadPosts()
}
func reload() {
collectionView.reloadData()
refresher.endRefreshing()
}
I assume that the UUID's are unique for every post, so you can check to see if the count from the previous load is different from the current, then you can see which posts are new, figure out their index path then only reload those index paths. I used sets to determine which id's had been added, which will work assuming you don't want to display the same post twice. There might be a better way of doing it, but in general you need to do something similar to the following:
func loadPosts() {
self.activityView.startAnimating()
let followQuery = PFQuery(className: "Follows")
followQuery.whereKey("follower", equalTo: PFUser.currentUser()!.username!)
followQuery.findObjectsInBackgroundWithBlock ({ (objects:[PFObject]?, error:NSError?) -> Void in
if error == nil {
self.followArray.removeAll(keepCapacity: false)
for object in objects! {
self.followArray.append(object.valueForKey("following") as! String)
}
let query = PFQuery(className: "Posts")
query.limit = self.page
query.whereKey("username", notContainedIn: self.followArray)
query.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query.findObjectsInBackgroundWithBlock ({ (objects:[PFObject]?, error:NSError?) -> Void in
if error == nil {
let oldUUIDArray = self.uuidArray
self.postImage.removeAll(keepCapacity: false)
self.uuidArray.removeAll(keepCapacity: false)
self.usernameArray.removeAll(keepCapacity: false)
for object in objects! {
self.postImage.append(object.valueForKey("image") as! PFFile)
self.uuidArray.append(object.valueForKey("uuid") as! String)
self.usernameArray.append(object.valueForKey("username") as! String)
}
let uuidOldSet = Set(oldUUIDArray)
let uuidNewSet = Set(self.uuidArray)
let missingUUIDs = uuidNewSet.subtract(uuidOldSet)
let missingUUIDArray = Array(missingUUIDs)
let missingUUIDIndexPaths = missingUUIDArray.map{NSIndexPath(forItem:self.uuidArray.indexOf($0)!,inSe ction:0)}
let extraUUIDs = uuidOldSet.subtract(uuidNewSet)
let extraUUIDArray = Array(extraUUIDs)
let extraUUIDIndexPaths = extraUUIDArray.map{NSIndexPath(forItem:oldUUIDArray.indexOf($0)!,inSection:0)}
self.collectionView.performBatchUpdates({
if extraUUIDIndexPath != nil {
self.collectionView.deleteItemsAtIndexPaths(extraUUIDIndexPaths)
}
if missingUUIDIndexPaths != nil {self.collectionView.insertItemsAtIndexPaths(missingUUIDIndexPaths)}
}, completion: nil)
} else {
print(error!.localizedDescription)
}
self.refresher.endRefreshing()
self.activityView.stopAnimating()
self.boxView.removeFromSuperview()
})
}
})
}
func reload() {
self.loadPosts()
refresher.endRefreshing()
}
I'm using a Parse account to post images, messages and username to a prototype cell. For some reason my username string is staying empty and thus not posting to the cell. Can you help? I'm fairly new to coding so this one has just stumped me.
import UIKit
import Parse
class FeedTableViewController: UITableViewController {
var messages = [String]()
var usernames = [String]()
var imageFiles = [PFFile]()
var users = [String: String]()
var refresher: UIRefreshControl!
#IBAction func logout(sender: AnyObject) {
PFUser.logOut()
var currentUser = PFUser.currentUser()
performSegueWithIdentifier("logout", sender: self)
}
func swiped(gesture:UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
performSegueWithIdentifier("feedSwipe", sender: self)
//case UISwipeGestureRecognizerDirection.Up:
//print("User Swiped Up")
//case UISwipeGestureRecognizerDirection.Down:
//print("User Swiped Down")
case UISwipeGestureRecognizerDirection.Left:
performSegueWithIdentifier("feedSwipe", sender: self)
default:
break
}
}
}
func refresh() {
var query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
self.messages.removeAll(keepCapacity: true)
self.users.removeAll(keepCapacity: true)
self.imageFiles.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
self.users[user.objectId!] = user.username!
}
}
}
var getFollowedUsersQuery = PFQuery(className: "followers")
getFollowedUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
var followedUser = object["following"] as! String
var query = PFQuery(className: "Post")
query.whereKey("userId", equalTo: followedUser)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.messages.append(object["message"]! as! String)
self.imageFiles.append(object["imageFile"]! as! PFFile)
self.usernames.append(self.users[object["userId"] as! String]!)
//self.usernames.append(followedUser)
self.tableView.reloadData()
self.refresher.endRefreshing()
//print(followedUser)
}
}
})
}
}
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeUp.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeDown.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipeDown)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(swipeLeft)
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
myCell.postedImage.image = downloadedImage
}
}
myCell.username.text = usernames[indexPath.row]
myCell.message.text = messages[indexPath.row]
return myCell
}
Here is function where I try to fetch images from parse for users that are in the namesArray.
func fetchData(){
let imagePredicate = NSPredicate(format: "username IN %#", namesArray)
let imageQuery = PFQuery(className: "_User", predicate: imagePredicate)
imageQuery.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
self.imagesArray.append(object["image"] as! PFFile)
if self.imagesArray.count == self.namesArray.count {
self.tableView.reloadData()
}
} else {
print("error: \(error?.localizedDescription)")
}
}
}
Here is my tableView:cellForRowAtIndexPath method:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ChatsCell
cell.nameLabel.text = namesArray[indexPath.row]
if imagesArray.count == namesArray.count && self.imagesLoaded == false{
imagesArray[indexPath.row].getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.imageView?.image = image
self.tableView.reloadData()
self.imagesLoaded = true
}
}
}
return cell
}
But when I do so I see that images are not synchronised with names of the users. Even if I put my users in other order images will stay in the same order as they was before.
How can I change it?
Not sure what you're asking here. Is it that you were expecting the images to be returned in an array sorted by the user?
If so, then you will need to add a sort order to your PFQuery. I suggest you sort your namesArray by username, and then also sort the imageQuery by username:
imageQuery.orderByDescending("username")
Hope I understood the question ;]
--T
So I found that if you use one query you will receive ordered data so I've changed my code and now it works pretty well. So what I've done is that I do query for every separate member of the namesArray:
func fetchData() {
for index in 0..<self.namesArray.count {
let imagePredicate = NSPredicate(format: "username == %#", namesArray[index])
let imageQuery = PFQuery(className: "_User", predicate: imagePredicate)
imageQuery.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
self.imageFilesArray![index] = object["image"] as? PFFile
}
for imageFile in self.imageFilesArray! {
let index = self.imageFilesArray?.indexOf{$0 == imageFile}
imageFile?.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
let userImage = UIImage(data: imageData!)
self.imagesArray?[index!] = userImage
self.tableView.reloadData()
})
}
}
})
}
}
and here is tableView:cellForRowAtIndexPath:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ChatsCell
cell.nameLabel.text = namesArray[indexPath.row]
cell.messageTextLabel.text = messagesArray[indexPath.row]
cell.chatImageView.image = self.imagesArray![indexPath.row] != nil ? self.imagesArray![indexPath.row] : UIImage(named: "add")
return cell
}
I keep receiving the following error:
in the logs i get
unexpectedly found nil while unwrapping an Optional value
the reason im having trouble with this is because i ran this code earlier and it worked fine can somebody please help and tell me where im going wrong in the code?
here is the full code
import UIKit
import Parse
class HomePage: UITableViewController {
var images = [UIImage]()
var titles = [String]()
var imageFile = [PFFile]()
var voteCounter = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
println(PFUser.currentUser())
var query = PFQuery(className:"Post")
var voteCount = PFObject(className: "Post")
voteCount["voteCounter"] = voteCounter
voteCount.saveInBackground()
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(objects!.count) scores.")
for object in objects! {
self.titles.append(object["Title"] as! String)
self.imageFile.append(object["imageFile"] as! PFFile)
self.tableView.reloadData()
}
} else {
// Log details of the failure
println(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 500
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var myCell:cell = self.tableView.dequeueReusableCellWithIdentifier("myCell") as! cell
myCell.rank.text = "21"
myCell.votes.text = "\(voteCounter)"
myCell.postDescription.text = titles[indexPath.row]
imageFile[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
myCell.postedImage.image = downloadedImage
}
}
var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
myCell.postedImage.userInteractionEnabled = true;
myCell.postedImage.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Left
myCell.postedImage.userInteractionEnabled = true;
myCell.postedImage.addGestureRecognizer(swipeLeft)
return myCell
}
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
var voteCounter = 0
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
voteCounter += 1
println("Swiped right")
case UISwipeGestureRecognizerDirection.Left:
voteCounter -= 1
println("Swiped Left")
default:
break
}
}
}
}
also any further advice or comments would be appreciated im fairly new to programming
Try this.
query.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(objects!.count) scores.")
for object in objects! {
if let dict = object as? [String: AnyObject] {
if let title = object["Title"] as? String {
self.titles.append(title)
}
if let imgFile = object["imageFile"] as? PFFile {
self.imageFile.append(imgFile)
}
}
self.tableView.reloadData()
}
} else {
// Log details of the failure
println(error)
}
}