SlideShare a Scribd company logo
Firebase: Totally Not
Parse All Over Again
(Unless It Is)
Chris Adamson (@invalidname)
CocoaConf San Jose • November, 2016
Slides available at slideshare.net/invalidname
Code available at github.com/invalidstream
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose, Nov. 2016)
Firebase
• Founded in 2011
• Offshoot of Envolve, a chat service that game
developers started using to sync state across
devices
• Main product is a realtime database
• Acquired by Google in October 2014
https://techcrunch.com/2016/05/18/google-turns-firebase-into-its-unified-
platform-for-mobile-developers/
Firebase @ Google
• 470,000 developers using Firebase
• Arguably the star of Google I/O 2016
• Analytics (from developers of Google
Analytics)
• Notifications (based on Google Cloud
Messaging)
Realtime database
• Cloud-based NoSQL database
• Syncs instantly across devices, handles going
offline
• Client SDKs for iOS and Android, REST for web
• Free tier supports 100 simultaneous users, 1GB
storage
Getting Started
• Create app on firebase.google.com using your
apps bundle identifier
• Download and add GoogleService-info.plist to
your project
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose, Nov. 2016)
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose, Nov. 2016)
Getting Started
• Add the Firebase Cocoapod
• As with all things pod, remember to
use .xcworkspace instead of .xcproj from now
on
• Yes, it is possible to add the frameworks
without Cocoapods
Getting Started
• Initialize Firebase in application(_:
didFinishLaunchingWithOptions:)
import Firebase
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
return true
}
Demo
Wait, what the…
• Firebase I/O works with a local cache, which in
turn syncs with the backend
• With good connectivity, syncing to backend
and other devices is instantaneous
• When offline, you can keep working with your
local db, which syncs when you’re back online
Tree-structured data
Tree-structured data
• Your database is basically one big JSON tree
• You access branches and nodes by path
• e.g., /sessions/adamson-firebase/title
• You can query at a given location, but this is not a
relational database.
• If you want to do a table join, you structured
your data incorrectly. Prefer flatness.
Getting a Firebase
Reference
• FIRDatabase.reference() returns root of tree as a
FIRDatabaseReference
• Child returns the named child as a
FIRDatabaseReference
firebaseSessions = FIRDatabase.database().reference().
child("sessions")
Now What?
Observing Firebase
• All interactions with Firebase are asynchronous
• You don’t read the value of a location, you
observe it for changes
• Contents of the child are passed to you on every
change
Observe!
• eventType: the type of event you want to
observe (value, child CRUD, etc)
• block: a closure to execute on these events
• returns a handle (dispose it in deinit, or earlier)
firebaseHandle = firebaseSessions?.observe(
FIRDataEventType.value, with: { [weak self] (snapshot) in
self?.parseSessionsFrom(snapshot)
self?.tableView.reloadData()
})
Parse!
• Observer block receives a FIRDataSnapshot for
every change
• Immutable, fetch contents with .value()
• Value types: NSDictionary, NSArray (rare),
NSString, NSNumber [or Swift equivalents]
Parse sessions list
private func parseSessionsFrom(_ snapshot: FIRDataSnapshot) {
guard let fbSessions = snapshot.value as? [String : Any]
else {
return
}
sessions.removeAll()
for (id, value) in fbSessions {
if let sessionDict = value as? [String : Any],
let session = Session(id: id, dict: sessionDict) {
sessions.append(session)
}
}
}
Parse a session
init? (id: String, dict : [String : Any]) {
guard let title = dict["title"] as? String,
let speakerName = dict["speakerName"] as? String,
let description = dict["description"] as? String
else
{
return nil
}
self.id = id
self.title = title
self.speakerName = speakerName
self.description = description
}
Note: id is the node name (the key in the dictionary
on the last slide)
Tip!
• FIRDatabaseReference.url can be pasted into
your browser to view the Firebase console for
that location in your db.
Demo: Writing data back to
Firebase
Creating a location
if let oldId = UserDefaults.standard.string(forKey:
"userId") {
firebaseUser = firebaseAttendees?.child(oldId)
} else {
firebaseUser = firebaseAttendees?.childByAutoId()
let newId = firebaseUser?.key
let firebaseUserName = firebaseUser?.child("name")
firebaseUserName?.setValue("Foo Bar")
UserDefaults.standard.setValue(newId,
forKey: "userId")
UserDefaults.standard.synchronize()
}
childByAutoId()
Setting a value
let firebaseUserFavorites = firebaseUser?.child("favorites")
let firebaseFavorite = firebaseUserFavorites?.child(sessionId)
firebaseFavorite?.setValue(true)
Lists of stuff
• Convention is to have a dict where keys are ids
and values are just “true”
Arrays in Firebase ಠ_ಠ
• A dictionary with numeric keys in order will be
sent to your observer as an array rather than a
dictionary
• Not as convenient as you’d think. Pretty much a
Firebase anti-pattern
observeSingleEvent()
favoriteTitles.removeAll()
for (sessionId, _) in fbFavorites {
firebaseSessions?.child(sessionId).child(“title").observeSingleEvent(
of: FIRDataEventType.value, with: { [weak self] snapshot in
if let title = snapshot.value as? String {
self?.favoriteTitles.append(
FavoriteItem(favoriteId: sessionId, title: title))
self?.tableView.reloadData()
}
})
}
Note: observeSingleEvent() does not return a handle
for you to hold on to and dispose later
Authentication
• Firebase provides an email + password system
• Can also use Google, Twitter, Facebook, or
GitHub credentials
• Or roll your own and provide an OAuth token
Database rules
• Define per-branch access based on
authentication
• Can require that user just be logged in, or that
their Firebase user id matches the one that
created the node
Default access
// These rules require authentication
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
Public access
// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}
Private access: just make read/write false
User access
// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}
Case Study
MathElf
• “Über for high-school math tutoring”
• Students request help on a topic, are paired with
a tutor in less than a minute
• Student and tutor work on problems via voice
chat and a shared whiteboard
MathElf Demo
MathElf & Firebase
• Authentication and user financials are done
through rev.com (parent company) backend,
making REST calls to Firebase
• Basically everything in the whiteboard and
session history is Firebase
User Metadata
Page Contents
Picture metadata
Drawing paths
mathelf.com
Firebase “con”s
• Limited visibility when something goes wrong
• When things don’t sync, is it them or you?
• Single point of failure, owned and operated by a
third party
• Could be Parse all over again
Takeaways
• Firebase database-as-a-service is well-suited to
mobile apps
• Real-time sync, still works when offline
• Structure your data as flat JSON trees, not SQL-
like tables
• All reads are asynchronous. Hope you like
closures/blocks.
Firebase: Totally Not
Parse All Over Again
(Unless It Is)
Chris Adamson (@invalidname)
CocoaConf San Jose • November, 2016
Slides available at slideshare.net/invalidname
Code available at github.com/invalidstream

More Related Content

PDF
Rapid Application Development with SwiftUI and Firebase
PDF
Devf (Shoe Lovers)
PPTX
SPSSTL - PowerShell - Through the SharePoint Looking Glass
PDF
s3
PDF
Web Development using Ruby on Rails
PDF
The What and Why of NoSql
PPTX
PowerShell: Through the SharePoint Looking Glass
PDF
Working with Terraform on Azure
Rapid Application Development with SwiftUI and Firebase
Devf (Shoe Lovers)
SPSSTL - PowerShell - Through the SharePoint Looking Glass
s3
Web Development using Ruby on Rails
The What and Why of NoSql
PowerShell: Through the SharePoint Looking Glass
Working with Terraform on Azure

What's hot (6)

PPTX
SPSTC - PowerShell - Through the SharePoint Looking Glass
PDF
Serverless architecture-patterns-and-best-practices
KEY
Scotch On The Rocks 2011
PDF
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
KEY
SOTR 2012
PPTX
Azure AD Connect
SPSTC - PowerShell - Through the SharePoint Looking Glass
Serverless architecture-patterns-and-best-practices
Scotch On The Rocks 2011
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
SOTR 2012
Azure AD Connect
Ad

Viewers also liked (16)

PDF
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
PDF
Get On The Audiobus (CocoaConf Atlanta, November 2013)
PDF
Get On The Audiobus (CocoaConf Boston, October 2013)
PDF
Stupid Video Tricks, CocoaConf Seattle 2014
PDF
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
PDF
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
PDF
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
PDF
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
PDF
Stupid Video Tricks (CocoaConf DC, March 2014)
PDF
Introduction to the Roku SDK
PDF
Firebase: Totally Not Parse All Over Again (Unless It Is)
PDF
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
PDF
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
PDF
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
PDF
Stupid Video Tricks
PDF
Stupid Video Tricks, CocoaConf Las Vegas
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Get On The Audiobus (CocoaConf Atlanta, November 2013)
Get On The Audiobus (CocoaConf Boston, October 2013)
Stupid Video Tricks, CocoaConf Seattle 2014
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Stupid Video Tricks (CocoaConf DC, March 2014)
Introduction to the Roku SDK
Firebase: Totally Not Parse All Over Again (Unless It Is)
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Stupid Video Tricks
Stupid Video Tricks, CocoaConf Las Vegas
Ad

Similar to Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose, Nov. 2016) (20)

PPTX
Firebase - A real-time server
PPTX
Advance Mobile Application Development class 07
PDF
Firebase Tech Talk By Atlogys
PDF
Firebase_not_really_yohoho
PPTX
Android and firebase database
PPTX
Firebase not really_yohoho
PPTX
Android writing and reading from firebase
PPTX
Introduction to Firebase
PDF
Online mobile game server use Firebase realtime aatabase
PPTX
Tech Winter Break - GDG OnCampus International Institute of Information Techn...
PPTX
Fire up your mobile app!
PPTX
Intoduction of FIrebase Realtime Database
PPTX
Firebase
PDF
Introduction to Firebase on Android
PPT
PPTX
What is new in Firebase?
PDF
Introducing Firebase by Google
PDF
Firebase-ized your mobile app
PDF
Google Firebase presentation - English
PDF
Realtime Database with iOS and Firebase
Firebase - A real-time server
Advance Mobile Application Development class 07
Firebase Tech Talk By Atlogys
Firebase_not_really_yohoho
Android and firebase database
Firebase not really_yohoho
Android writing and reading from firebase
Introduction to Firebase
Online mobile game server use Firebase realtime aatabase
Tech Winter Break - GDG OnCampus International Institute of Information Techn...
Fire up your mobile app!
Intoduction of FIrebase Realtime Database
Firebase
Introduction to Firebase on Android
What is new in Firebase?
Introducing Firebase by Google
Firebase-ized your mobile app
Google Firebase presentation - English
Realtime Database with iOS and Firebase

More from Chris Adamson (14)

PDF
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
PDF
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
PDF
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
PDF
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
PDF
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
PDF
Glitch-Free A/V Encoding (CocoaConf Boston, October 2013)
PDF
iOS Media APIs (MobiDevDay Detroit, May 2013)
PDF
Core Audio in iOS 6 (CocoaConf San Jose, April 2013)
PDF
Core Audio in iOS 6 (CocoaConf DC, March 2013)
PDF
Mobile Movies with HTTP Live Streaming (CocoaConf DC, March 2013)
PDF
Core Audio in iOS 6 (CocoaConf Chicago, March 2013)
PDF
Core Audio Intro (Detroit Mobile City 2013)
PDF
Objective-C Is Not Java
PDF
Core Audio in iOS 6 (CocoaConf Raleigh, Dec. '12)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
Glitch-Free A/V Encoding (CocoaConf Boston, October 2013)
iOS Media APIs (MobiDevDay Detroit, May 2013)
Core Audio in iOS 6 (CocoaConf San Jose, April 2013)
Core Audio in iOS 6 (CocoaConf DC, March 2013)
Mobile Movies with HTTP Live Streaming (CocoaConf DC, March 2013)
Core Audio in iOS 6 (CocoaConf Chicago, March 2013)
Core Audio Intro (Detroit Mobile City 2013)
Objective-C Is Not Java
Core Audio in iOS 6 (CocoaConf Raleigh, Dec. '12)

Recently uploaded (20)

PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Essential Infomation Tech presentation.pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
System and Network Administraation Chapter 3
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Understanding Forklifts - TECH EHS Solution
PDF
medical staffing services at VALiNTRY
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administration Chapter 2
Softaken Excel to vCard Converter Software.pdf
Upgrade and Innovation Strategies for SAP ERP Customers
Essential Infomation Tech presentation.pptx
Odoo POS Development Services by CandidRoot Solutions
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
System and Network Administraation Chapter 3
Odoo Companies in India – Driving Business Transformation.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Understanding Forklifts - TECH EHS Solution
medical staffing services at VALiNTRY
Wondershare Filmora 15 Crack With Activation Key [2025
CHAPTER 2 - PM Management and IT Context
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Design an Analysis of Algorithms I-SECS-1021-03
2025 Textile ERP Trends: SAP, Odoo & Oracle
L1 - Introduction to python Backend.pptx
System and Network Administration Chapter 2

Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose, Nov. 2016)

  • 1. Firebase: Totally Not Parse All Over Again (Unless It Is) Chris Adamson (@invalidname) CocoaConf San Jose • November, 2016 Slides available at slideshare.net/invalidname Code available at github.com/invalidstream
  • 3. Firebase • Founded in 2011 • Offshoot of Envolve, a chat service that game developers started using to sync state across devices • Main product is a realtime database • Acquired by Google in October 2014
  • 5. Firebase @ Google • 470,000 developers using Firebase • Arguably the star of Google I/O 2016 • Analytics (from developers of Google Analytics) • Notifications (based on Google Cloud Messaging)
  • 6. Realtime database • Cloud-based NoSQL database • Syncs instantly across devices, handles going offline • Client SDKs for iOS and Android, REST for web • Free tier supports 100 simultaneous users, 1GB storage
  • 7. Getting Started • Create app on firebase.google.com using your apps bundle identifier • Download and add GoogleService-info.plist to your project
  • 10. Getting Started • Add the Firebase Cocoapod • As with all things pod, remember to use .xcworkspace instead of .xcproj from now on • Yes, it is possible to add the frameworks without Cocoapods
  • 11. Getting Started • Initialize Firebase in application(_: didFinishLaunchingWithOptions:) import Firebase func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FIRApp.configure() return true }
  • 12. Demo
  • 13. Wait, what the… • Firebase I/O works with a local cache, which in turn syncs with the backend • With good connectivity, syncing to backend and other devices is instantaneous • When offline, you can keep working with your local db, which syncs when you’re back online
  • 15. Tree-structured data • Your database is basically one big JSON tree • You access branches and nodes by path • e.g., /sessions/adamson-firebase/title • You can query at a given location, but this is not a relational database. • If you want to do a table join, you structured your data incorrectly. Prefer flatness.
  • 16. Getting a Firebase Reference • FIRDatabase.reference() returns root of tree as a FIRDatabaseReference • Child returns the named child as a FIRDatabaseReference firebaseSessions = FIRDatabase.database().reference(). child("sessions")
  • 18. Observing Firebase • All interactions with Firebase are asynchronous • You don’t read the value of a location, you observe it for changes • Contents of the child are passed to you on every change
  • 19. Observe! • eventType: the type of event you want to observe (value, child CRUD, etc) • block: a closure to execute on these events • returns a handle (dispose it in deinit, or earlier) firebaseHandle = firebaseSessions?.observe( FIRDataEventType.value, with: { [weak self] (snapshot) in self?.parseSessionsFrom(snapshot) self?.tableView.reloadData() })
  • 20. Parse! • Observer block receives a FIRDataSnapshot for every change • Immutable, fetch contents with .value() • Value types: NSDictionary, NSArray (rare), NSString, NSNumber [or Swift equivalents]
  • 21. Parse sessions list private func parseSessionsFrom(_ snapshot: FIRDataSnapshot) { guard let fbSessions = snapshot.value as? [String : Any] else { return } sessions.removeAll() for (id, value) in fbSessions { if let sessionDict = value as? [String : Any], let session = Session(id: id, dict: sessionDict) { sessions.append(session) } } }
  • 22. Parse a session init? (id: String, dict : [String : Any]) { guard let title = dict["title"] as? String, let speakerName = dict["speakerName"] as? String, let description = dict["description"] as? String else { return nil } self.id = id self.title = title self.speakerName = speakerName self.description = description } Note: id is the node name (the key in the dictionary on the last slide)
  • 23. Tip! • FIRDatabaseReference.url can be pasted into your browser to view the Firebase console for that location in your db.
  • 24. Demo: Writing data back to Firebase
  • 25. Creating a location if let oldId = UserDefaults.standard.string(forKey: "userId") { firebaseUser = firebaseAttendees?.child(oldId) } else { firebaseUser = firebaseAttendees?.childByAutoId() let newId = firebaseUser?.key let firebaseUserName = firebaseUser?.child("name") firebaseUserName?.setValue("Foo Bar") UserDefaults.standard.setValue(newId, forKey: "userId") UserDefaults.standard.synchronize() }
  • 27. Setting a value let firebaseUserFavorites = firebaseUser?.child("favorites") let firebaseFavorite = firebaseUserFavorites?.child(sessionId) firebaseFavorite?.setValue(true)
  • 28. Lists of stuff • Convention is to have a dict where keys are ids and values are just “true”
  • 29. Arrays in Firebase ಠ_ಠ • A dictionary with numeric keys in order will be sent to your observer as an array rather than a dictionary • Not as convenient as you’d think. Pretty much a Firebase anti-pattern
  • 30. observeSingleEvent() favoriteTitles.removeAll() for (sessionId, _) in fbFavorites { firebaseSessions?.child(sessionId).child(“title").observeSingleEvent( of: FIRDataEventType.value, with: { [weak self] snapshot in if let title = snapshot.value as? String { self?.favoriteTitles.append( FavoriteItem(favoriteId: sessionId, title: title)) self?.tableView.reloadData() } }) } Note: observeSingleEvent() does not return a handle for you to hold on to and dispose later
  • 31. Authentication • Firebase provides an email + password system • Can also use Google, Twitter, Facebook, or GitHub credentials • Or roll your own and provide an OAuth token
  • 32. Database rules • Define per-branch access based on authentication • Can require that user just be logged in, or that their Firebase user id matches the one that created the node
  • 33. Default access // These rules require authentication {   "rules": {     ".read": "auth != null",     ".write": "auth != null"   } }
  • 34. Public access // These rules give anyone, even people who are not users of your app, // read and write access to your database {   "rules": {     ".read": true,     ".write": true   } } Private access: just make read/write false
  • 35. User access // These rules grant access to a node matching the authenticated // user's ID from the Firebase auth token {   "rules": {     "users": {       "$uid": {         ".read": "$uid === auth.uid",         ".write": "$uid === auth.uid"       }     }   } }
  • 37. MathElf • “Über for high-school math tutoring” • Students request help on a topic, are paired with a tutor in less than a minute • Student and tutor work on problems via voice chat and a shared whiteboard
  • 39. MathElf & Firebase • Authentication and user financials are done through rev.com (parent company) backend, making REST calls to Firebase • Basically everything in the whiteboard and session history is Firebase
  • 45. Firebase “con”s • Limited visibility when something goes wrong • When things don’t sync, is it them or you? • Single point of failure, owned and operated by a third party • Could be Parse all over again
  • 46. Takeaways • Firebase database-as-a-service is well-suited to mobile apps • Real-time sync, still works when offline • Structure your data as flat JSON trees, not SQL- like tables • All reads are asynchronous. Hope you like closures/blocks.
  • 47. Firebase: Totally Not Parse All Over Again (Unless It Is) Chris Adamson (@invalidname) CocoaConf San Jose • November, 2016 Slides available at slideshare.net/invalidname Code available at github.com/invalidstream