Skip to content

Instantly share code, notes, and snippets.

@AmbroiseCollon
Created July 9, 2016 16:09
Show Gist options
  • Save AmbroiseCollon/af54f8514cdbae1a49bc72b769d64580 to your computer and use it in GitHub Desktop.
Save AmbroiseCollon/af54f8514cdbae1a49bc72b769d64580 to your computer and use it in GitHub Desktop.
Parse Live Query tableview
import Foundation
import Parse
import ParseLiveQuery
extension _ArrayType where Generator.Element == PFObject {
mutating func updateWithEvent(event: Event<PFObject>) {
switch event {
case .Created(let object):
append(object)
case .Entered(let object):
append(object)
case .Deleted(let object):
if let index = indexOf(object) {
removeAtIndex(index)
}
case .Left(let object):
if let index = indexOf(object) {
removeAtIndex(index)
}
case .Updated(let object):
if let index = indexOf(object) {
self[index] = object
}
}
}
}
import UIKit
import Parse
import ParseLiveQuery
class TableViewController: UITableViewController {
// MARK: - Properties
var games = [PFObject]() {
didSet {
tableView.reloadData()
}
}
var myQuery: PFQuery? {
return MyPFSubclassObject.query()?
.whereKey(myKey, equalTo: "Something")
.orderByAscending("createdAt")
}
private var subscription: Subscription<Game>?
// MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
load()
}
/**
Load games from DB
*/
func load() {
myQuery?.findObjectsInBackgroundWithBlock({ (objects, error) in
if error == nil {
if let objects = objects {
self.games = objects
self.subscribeToUpdates()
}
} else {
print("error : \(error?.userInfo)")
}
})
}
/**
Check for any update and modify games property accordingly
*/
func subscribeToUpdates() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// Live query client is created in app delegate and available as a property
if let liveQueryClient = appDelegate.liveQueryClient, myQuery = myQuery {
subscription = liveQueryClient
.subscribe(myQuery)
.handleEvent { _, event in
self.games.updateWithEvent(event)
}
}
}
// Classic table view logic continues with games as data source
}
@ShawnBaek
Copy link

Hi thanks for sharing great example.

If you have a free time could you advising me?

Here is my question

http://stackoverflow.com/questions/40653939/how-to-use-parselivequery-in-tableview

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment