Skip to content

Instantly share code, notes, and snippets.

View phucnm's full-sized avatar
😬
eager to learn

Tony Nguyen phucnm

😬
eager to learn
  • Vancouver, BC, Canada
View GitHub Profile
func getPost() -> Observable<Post> {
let postRef = Database.database().reference()
.child("posts")
return postRef.rx_observeEvent(event: .childAdded)
.map { Post(snapshot: $0) }
.unwrap()
}
getPost()
//It will emit an Error Event in case timed out
class Post: Mappable {
var postId: String?
var title: String?
var content: String?
var author: String?
var likes: [String]?
func mapping(map: Map) {
postId <- map[Post.firebaseIdKey]
title <- map["title"]
class DictionaryKeyTransform: TransformType {
typealias Object = [String]
typealias JSON = [String: Bool]
func transformFromJSON(_ value: Any?) -> [String]? {
guard let v = value as? JSON else { return [String]() }
return Array(v.keys)
}
func transformToJSON(_ value: [String]?) -> [String : Bool]? {
func getPosts() -> Observable<[Post]> {
let postRef = Database.database().reference()
.child("posts")
return postRef.rx_observeSingleEvent(of: .value)
.map { Mapper<Post>().mapArray(snapshot: $0) }
}
getPosts().subscribe(onNext: { posts in
//show the data or do whatever you want
}, onError: { error in
extension DatabaseQuery {
func rx_observeSingleEvent(of event: DataEventType) -> Observable<DataSnapshot> {
return Observable.create({ (observer) -> Disposable in
self.observeSingleEvent(of: event, with: { (snapshot) in
observer.onNext(snapshot)
observer.onCompleted()
}, withCancel: { (error) in
observer.onError(error)
})
extension Mapper {
func mapArray(snapshot: DataSnapshot) -> [N] {
return snapshot.children.map { (child) -> N? in
if let childSnap = child as? DataSnapshot {
return N(snapshot: childSnap)
}
return nil
//flatMap here is a trick
//to filter out `nil` values
}.flatMap { $0 }
func getPost(postId: String, completion:@escaping ((Post?) -> Void)) {
let postRef = Database.database()
.reference().child("posts").child("postId")
postRef.observeSingleEvent(of: .value, with: { (snapshot) in
completion(Post(snapshot: snapshot))
})
}
extension BaseMappable {
static var firebaseIdKey : String {
get {
return "FirebaseIdKey"
}
}
init?(snapshot: DataSnapshot) {
guard var json = snapshot.value as? [String: Any] else {
return nil
}
@phucnm
phucnm / FirstPostModel.swift
Last active August 11, 2017 09:48
First-Post-Model
class Post: Mappable {
var postId: String?
var title: String?
var content: String?
var author: String?
func mapping(map: Map) {
postId <- map["postId"]
title <- map["title"]
content <- map["content"]
@phucnm
phucnm / gist:7ab09b99bb32709dce7848fac8cb2a53
Created March 21, 2017 04:53
How to disable deselect a table view cell
//Implement this delegate function
- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
if (<#condition#>) {
return nil;
}
return indexPath;
}
//To disable selection a table view cell
//Implement tableView:willSelectRowAtIndexPath: