SlideShare a Scribd company logo
Firebase: Totally Not
Parse All Over Again
(Unless It Is)
Chris Adamson (@invalidname)
CocoaConf DC • September, 2016
Slides will be available at slideshare.net/invalidname
Code will be available at github.com/invalidstream
Firebase: Totally Not Parse All Over Again (Unless It Is)
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)
Firebase: Totally Not Parse All Over Again (Unless It Is)
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 DC • September, 2016
Slides will be available at slideshare.net/invalidname
Code will be 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)
PPTX
Azure AD Connect
KEY
SOTR 2012
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)
Azure AD Connect
SOTR 2012
Ad

Viewers also liked (18)

PDF
The Firebase tier for your mobile app - DevFest CH
PDF
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
PDF
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
PDF
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
PDF
Get On The Audiobus (CocoaConf Atlanta, November 2013)
PDF
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
PDF
Get On The Audiobus (CocoaConf Boston, October 2013)
PDF
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
PDF
Stupid Video Tricks, CocoaConf Seattle 2014
PDF
Stupid Video Tricks (CocoaConf DC, March 2014)
PDF
Introduction to the Roku SDK
PDF
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
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 Atlanta, December 2014
PDF
Stupid Video Tricks
PDF
Stupid Video Tricks, CocoaConf Las Vegas
PDF
Introduction to Firebase from Google
PDF
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
The Firebase tier for your mobile app - DevFest CH
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Get On The Audiobus (CocoaConf Atlanta, November 2013)
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Get On The Audiobus (CocoaConf Boston, October 2013)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks (CocoaConf DC, March 2014)
Introduction to the Roku SDK
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
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 Atlanta, December 2014
Stupid Video Tricks
Stupid Video Tricks, CocoaConf Las Vegas
Introduction to Firebase from Google
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Ad

Similar to Firebase: Totally Not Parse All Over Again (Unless It Is) (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
Firebase not really_yohoho
PPTX
Android and firebase database
PPTX
Introduction to Firebase
PPTX
Android writing and reading from firebase
PPTX
Tech Winter Break - GDG OnCampus International Institute of Information Techn...
PDF
Online mobile game server use Firebase realtime aatabase
PPTX
Fire up your mobile app!
PPTX
Intoduction of FIrebase Realtime Database
PPTX
Firebase
PDF
Introduction to Firebase on Android
PDF
Introducing Firebase by Google
PPT
PDF
Google Firebase presentation - English
PPTX
What is new in Firebase?
PDF
Firebase-ized your mobile app
PPTX
Firebasics
Firebase - A real-time server
Advance Mobile Application Development class 07
Firebase Tech Talk By Atlogys
Firebase_not_really_yohoho
Firebase not really_yohoho
Android and firebase database
Introduction to Firebase
Android writing and reading from firebase
Tech Winter Break - GDG OnCampus International Institute of Information Techn...
Online mobile game server use Firebase realtime aatabase
Fire up your mobile app!
Intoduction of FIrebase Realtime Database
Firebase
Introduction to Firebase on Android
Introducing Firebase by Google
Google Firebase presentation - English
What is new in Firebase?
Firebase-ized your mobile app
Firebasics

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
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Essential Infomation Tech presentation.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
System and Network Administraation Chapter 3
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
medical staffing services at VALiNTRY
PPTX
Introduction to Artificial Intelligence
PDF
AI in Product Development-omnex systems
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
top salesforce developer skills in 2025.pdf
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
How Creative Agencies Leverage Project Management Software.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Essential Infomation Tech presentation.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Operating system designcfffgfgggggggvggggggggg
Design an Analysis of Algorithms I-SECS-1021-03
System and Network Administraation Chapter 3
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Odoo Companies in India – Driving Business Transformation.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
medical staffing services at VALiNTRY
Introduction to Artificial Intelligence
AI in Product Development-omnex systems
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Internet Downloader Manager (IDM) Crack 6.42 Build 41
top salesforce developer skills in 2025.pdf
Navsoft: AI-Powered Business Solutions & Custom Software Development
VVF-Customer-Presentation2025-Ver1.9.pptx
Design an Analysis of Algorithms II-SECS-1021-03
Reimagine Home Health with the Power of Agentic AI​
How Creative Agencies Leverage Project Management Software.pdf

Firebase: Totally Not Parse All Over Again (Unless It Is)

  • 1. Firebase: Totally Not Parse All Over Again (Unless It Is) Chris Adamson (@invalidname) CocoaConf DC • September, 2016 Slides will be available at slideshare.net/invalidname Code will be 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 DC • September, 2016 Slides will be available at slideshare.net/invalidname Code will be available at github.com/invalidstream