Skip to content

Instantly share code, notes, and snippets.

@zaneclaes
Created May 3, 2014 15:59
Show Gist options
  • Save zaneclaes/566af446a52dc007a43e to your computer and use it in GitHub Desktop.
Save zaneclaes/566af446a52dc007a43e to your computer and use it in GitHub Desktop.
//
// SNFirebase.m
// SharedNotes
//
// Created by Zane Claes on 4/12/14.
// Copyright (c) 2014 inZania LLC. All rights reserved.
//
#import "SNFirebase.h"
#import <Firebase/Firebase.h>
@implementation NSDictionary (DeepCopy)
- (NSMutableDictionary *)mutableDeepCopy
{
return (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)self, kCFPropertyListMutableContainers));
}
@end
@interface SNFirebase ()
@property (nonatomic, strong) NSString *firebaseURL;
@end
@implementation SNFirebase
- (void)save:(void (^)(BOOL success))completionHandler {
// Use a copied firebase, so that we don't create race conditions
// Firebase uses a different thread, and will throw mutation exceptions
Firebase *fb = [[Firebase alloc] initWithUrl:self.firebaseURL];
[fb setValue:[self.contents copy] withCompletionBlock:^(NSError *error, Firebase *ref) {
if(completionHandler) {
completionHandler(error ? NO : YES);
}
}];
}
- (void)save {
[self save:nil];
}
- (void)load:(void (^)(BOOL success))block {
Firebase *fb = [[Firebase alloc] initWithUrl:self.firebaseURL];
[fb observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
_contents = [[snapshot.value isKindOfClass:[NSDictionary class]]?snapshot.value:@{} mutableDeepCopy];
block(_contents.allKeys.count > 0);
}];
}
- (Firebase*)firebase {
return [[Firebase alloc] initWithUrl:self.firebaseURL];
}
- (id)initWithFirebase:(Firebase*)firebase contents:(NSDictionary*)contents {
if((self = [super init])) {
_firebaseURL = firebase.description;
_contents = [contents?:@{} mutableDeepCopy];
}
return self;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment