Skip to content

Instantly share code, notes, and snippets.

@ShawnBaek
Forked from AmbroiseCollon/LiveQuerryArray.swift
Last active December 16, 2016 07:22
Show Gist options
  • Save ShawnBaek/7a91811e944599666df0a44288a11f88 to your computer and use it in GitHub Desktop.
Save ShawnBaek/7a91811e944599666df0a44288a11f88 to your computer and use it in GitHub Desktop.
Parse Livechat
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 Foundation
import Parse
import ParseLiveQuery
extension _ArrayProtocol where Iterator.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 = index(of: object) {
remove(at: index)
}
case .left(let object):
if let index = index(of: object) {
remove(at: index)
}
case .updated(let object):
if let index = index(of: object) {
//I got an error : Cannot assign through subscript: subscript is get-only
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment