SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
Rapid Application Development 

with SwiftUI and Firebase
Peter Friese, Developer Advocate, Google
@peterfriese
🔥
Demo 1

Kaffeinated - A coffee tracking app
SwiftUI
• A declarative way to build your UI

• Everything is a view

• Every SwiftUI view is a struct

• You build UIs by composing views
• Views are a function of their state
Better state management!
struct ContentView: View {
var body: some View {
Text("Hello, World!")
}
}
SwiftUI Views
Demo 2
Building a List From Scratch
Improve app quality
Crashlytics
Performance
Monitoring
Test Lab
App Distribution
Grow your app
Analytics
Predictions
Cloud
Messaging
Remote
Config
A/B Testing
Dynamic

Links
In-app
Messaging
Build better apps
Auth
Cloud
Functions
Cloud
Firestore
Hosting
ML Kit
Realtime

Database
Cloud
Storage
bit.ly/what-is-firebase
Mobile Databases - The Hard Way
Database MongoDB, Postgres, MySQL, etc
API Server REST API on top of database
Auth Service Protects the API server
Sync Logic REST API calls, caches, etc
SQLite Store data offline
Cross-platform?
You're going to have to write the
same code multiple times!
App DatabaseServer
One-Time FetchesOffline ModeEffortless Syncing
Document
bird_type:
airspeed:
coconut_capacity:
isNative:
icon:
vector:
distances_traveled:
"swallow"
42.733
0.62
false
<binary data>
{x: 36.4255,
y: 25.1442,
z: 18.8816
[42, 39, 12,
42]
Collection
collection("restaurants").
where("city", " ==", "Cairo").
orderBy(“rating”, "desc").limit(10)
Here ya go!
Add Firebase to Your iOS Project
1. Create a new Firebase project

2. Register your iOS app

3. Download configuration file

4. Install the Firebase Cocoapod

5. Call FirebaseApp.configure()
Kaffeinated Data Model
Fetching Data from Firestore
db.collection("coffees").addSnapshotListener { (querySnapshot, error) in
var coffees = [Coffee]()
querySnapshot ?.documents.forEach { document in
let coffeeName = document.data()["name"] as? String ?? ""
let shortDescription = document.data()["shortDescription"] as? String ?? ""
let description = document.data()["description"] as? String ?? ""
let caffeineAmount = document.data()["caffeineAmount"] as? Int ?? 0
let coffee = Coffee(name: coffeeName,
shortDescription: shortDescription,
description: description,
caffeineAmount: caffeineAmount)
coffees.append(coffee)
}
self.coffees = coffees
}
Fetching Data from Firestore
Firestore & Codable
• One of our most-requested and
longest-running feature requests

• Released on October 22nd, 2019

• Makes fetching and writing much
easier
db.collection("coffees").addSnapshotListener { (querySnapshot, error) in
var coffees = [Coffee]()
querySnapshot ?.documents.forEach { document in
let coffeeName = document.data()["name"] as? String ?? ""
let shortDescription = document.data()["shortDescription"] as? String ?? ""
let description = document.data()["description"] as? String ?? ""
let caffeineAmount = document.data()["caffeineAmount"] as? Int ?? 0
let coffee = Coffee(name: coffeeName,
shortDescription: shortDescription,
description: description,
caffeineAmount: caffeineAmount)
coffees.append(coffee)
}
self.coffees = coffees
}
Fetching Data - w/o Codable
// Model
struct Coffee: Codable, Identifiable {
@DocumentID var id: String?
var name: String
var shortDescription: String
var description: String
}
// Elsewhere, fetch our data:
db.collection("coffees").addSnapshotListener { (querySnapshot, error) in
if let querySnapshot = querySnapshot {
self.coffees = querySnapshot.documents.compactMap { document -> Coffee? in
try? document.data(as: Coffee.self)
}
}
}
Fetching Data - w/ Codable
Saving Data to Firestore
let db = Firestore.firestore()
do {
_ = try db.collection(“users/(user.uid)/consumption/")
.addDocument(from: consumption)
}
catch {
print(“Error: (error.localizedDescription).")
}
Saving Data to Firestore
let db = Firestore.firestore()
do {
_ = try db.collection(“users/(user.uid)/consumption/")
.addDocument(from: consumption)
}
catch {
print(“Error: (error.localizedDescription).")
}
Saving Data to Firestore
We didn’t sign in, so what’s
this kind of magic?
Anonymous Auth
Auth.auth().signInAnonymously() { (authResult, error) in
guard let user = authResult ?.user else { return }
let isAnonymous = user.isAnonymous // true
let uid = user.uid
}
Anonymous Auth
let db = Firestore.firestore()
do {
_ = try db.collection(“users/(user.uid)/consumption/")
.addDocument(from: consumption)
}
catch {
print(“Error: (error.localizedDescription).")
}
Saving Data to Firestore
Data Flow
Data Flow
• Property

• @State

• @Binding

• @ObservedObject

• @EnvironmentObject

• Sarah Reichelt: SwiftUI Data Flow
(bit.ly/SwiftUIDataFlow)
struct BarsView: View {
let bars: [Bar]
let max: Double
init(bars: [Bar]) {
self.bars = bars
self.max = bars.map { $0.value }.max() ?? 0
}
var body: some View {
GeometryReader { geometry in
HStack(alignment: .bottom, spacing: 0) {
ForEach(self.bars) { bar in
Rectangle()
.fill(bar.color)
.frame(width: 10,
height: CGFloat(bar.value) /
CGFloat(self.max) * geometry.size.height)
Data Flow - Property
struct MainView: View {
@State var selectedTab = 0
@EnvironmentObject var appState: AppState
var body: some View {
TabView(selection: $selectedTab) {
}
}
}
Data Flow - @State
class CoffeeListViewModel: ObservableObject {
@Published var coffees: [Coffee]
}
struct CoffeeListView: View {
@ObservedObject var viewModel: CoffeeListViewModel
var body: some View {
NavigationView {
List(viewModel.coffees) { coffee in
CoffeeCell(coffee: coffee)
}
.navigationBarTitle("Coffees")
}
}
}
Data Flow - @ObservableObject
class AppState: ObservableObject {
@Published var coffees = [Coffee]()
@Published var consumptions = [Consumption]()
}
let appState = AppState()
let contentView = MainView()
window.rootViewController =
UIHostingController(rootView: contentView.environmentObject(appState))
struct MainView: View {
@EnvironmentObject var appState: AppState
var body: some View {
HistoryView(viewModel: HistoryViewModel(consumption: appState.consumptions))
.tabItem { Image(systemName: “chart.bar.fill”)) }
}
}
Data Flow - @EnvironmentObject
Data Flow for Firebase Apps
MainViewAppState
[Coffee]
[Consumption]
User
...
Environment
CoffeeListView
CoffeeListVM
[Coffee]
Firestore
Demo 3
The Final App, Using Firebase
Conclusion
Conclusion
• Achieve great results in a short amount of time

• Documentation a bit lacking

• Great contributions from the community

• A number of things don’t work (yet)

• Fill the gaps with UIViewControllerRepresentable
Conclusion
• Work together well

• No critical issues so far

• Firebase team eager to hear from the community
+
❤
Thanks! Peter Friese, Developer Advocate, Google
@peterfriese
https://peterfriese.dev

https://medium.com/@peterfriese
https://medium.com/firebase-developers

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Entity Relationships in a Document Database at CouchConf Boston
Entity Relationships in a Document Database at CouchConf BostonEntity Relationships in a Document Database at CouchConf Boston
Entity Relationships in a Document Database at CouchConf Boston
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 
Introduction to Azure Resource Manager, Global Azure Bootcamp 2016.04
Introduction to Azure Resource Manager, Global Azure Bootcamp 2016.04Introduction to Azure Resource Manager, Global Azure Bootcamp 2016.04
Introduction to Azure Resource Manager, Global Azure Bootcamp 2016.04
 
AWS January 2016 Webinar Series - Managing your Infrastructure as Code
AWS January 2016 Webinar Series - Managing your Infrastructure as CodeAWS January 2016 Webinar Series - Managing your Infrastructure as Code
AWS January 2016 Webinar Series - Managing your Infrastructure as Code
 
Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)
 
AWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWSAWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWS
 
Firebase for Apple Developers
Firebase for Apple DevelopersFirebase for Apple Developers
Firebase for Apple Developers
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with MongoDB
 
Multi screen HTML5
Multi screen HTML5Multi screen HTML5
Multi screen HTML5
 
System browser
System browserSystem browser
System browser
 
Deep Dive: AWS CloudFormation
Deep Dive: AWS CloudFormationDeep Dive: AWS CloudFormation
Deep Dive: AWS CloudFormation
 
RESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nicRESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nic
 
Deep-Dive to Azure Search
Deep-Dive to Azure SearchDeep-Dive to Azure Search
Deep-Dive to Azure Search
 
jQuery Mobile Workshop
jQuery Mobile WorkshopjQuery Mobile Workshop
jQuery Mobile Workshop
 
MongoDB and Hadoop: Driving Business Insights
MongoDB and Hadoop: Driving Business InsightsMongoDB and Hadoop: Driving Business Insights
MongoDB and Hadoop: Driving Business Insights
 
Android writing and reading from firebase
Android writing and reading from firebaseAndroid writing and reading from firebase
Android writing and reading from firebase
 
HTTP API for Free? Check out CouchDB
HTTP API for Free? Check out CouchDBHTTP API for Free? Check out CouchDB
HTTP API for Free? Check out CouchDB
 
Building Event-driven Serverless Applications
Building Event-driven Serverless ApplicationsBuilding Event-driven Serverless Applications
Building Event-driven Serverless Applications
 
【AWS Developers Meetup】RESTful APIをChaliceで紐解く
【AWS Developers Meetup】RESTful APIをChaliceで紐解く【AWS Developers Meetup】RESTful APIをChaliceで紐解く
【AWS Developers Meetup】RESTful APIをChaliceで紐解く
 
AWS May Webinar Series - Deep Dive: Infrastructure as Code
AWS May Webinar Series - Deep Dive: Infrastructure as CodeAWS May Webinar Series - Deep Dive: Infrastructure as Code
AWS May Webinar Series - Deep Dive: Infrastructure as Code
 

Ähnlich wie Rapid Application Development with SwiftUI and Firebase

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
Kiril Iliev
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
lanslote
 
DataFinder concepts and example: General (20100503)
DataFinder concepts and example: General (20100503)DataFinder concepts and example: General (20100503)
DataFinder concepts and example: General (20100503)
Data Finder
 
SharePoint 2010 Application Development Overview
SharePoint 2010 Application Development OverviewSharePoint 2010 Application Development Overview
SharePoint 2010 Application Development Overview
Rob Windsor
 

Ähnlich wie Rapid Application Development with SwiftUI and Firebase (20)

OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchApps
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
Going Serverless with Azure Functions
Going Serverless with Azure FunctionsGoing Serverless with Azure Functions
Going Serverless with Azure Functions
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
Spring 3 - An Introduction
Spring 3 - An IntroductionSpring 3 - An Introduction
Spring 3 - An Introduction
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
 
Code First with Serverless Azure Functions
Code First with Serverless Azure FunctionsCode First with Serverless Azure Functions
Code First with Serverless Azure Functions
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
 
Couchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemCouchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problem
 
DataFinder concepts and example: General (20100503)
DataFinder concepts and example: General (20100503)DataFinder concepts and example: General (20100503)
DataFinder concepts and example: General (20100503)
 
REST easy with API Platform
REST easy with API PlatformREST easy with API Platform
REST easy with API Platform
 
Chris O'Brien - Best bits of Azure for Office 365/SharePoint developers
Chris O'Brien - Best bits of Azure for Office 365/SharePoint developersChris O'Brien - Best bits of Azure for Office 365/SharePoint developers
Chris O'Brien - Best bits of Azure for Office 365/SharePoint developers
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
Tearing the Sofa Apart: CouchDB and CouchApps from a Beginner's Perspective
Tearing the Sofa Apart: CouchDB and CouchApps from a Beginner's PerspectiveTearing the Sofa Apart: CouchDB and CouchApps from a Beginner's Perspective
Tearing the Sofa Apart: CouchDB and CouchApps from a Beginner's Perspective
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
 
SharePoint 2010 Application Development Overview
SharePoint 2010 Application Development OverviewSharePoint 2010 Application Development Overview
SharePoint 2010 Application Development Overview
 

Mehr von Peter Friese

Mehr von Peter Friese (20)

Building Reusable SwiftUI Components
Building Reusable SwiftUI ComponentsBuilding Reusable SwiftUI Components
Building Reusable SwiftUI Components
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI Workshop
 
Building Reusable SwiftUI Components
Building Reusable SwiftUI ComponentsBuilding Reusable SwiftUI Components
Building Reusable SwiftUI Components
 
Firebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesFirebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroes
 
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Building Apps with SwiftUI and Firebase
Building Apps with SwiftUI and FirebaseBuilding Apps with SwiftUI and Firebase
Building Apps with SwiftUI and Firebase
 
6 Things You Didn't Know About Firebase Auth
6 Things You Didn't Know About Firebase Auth6 Things You Didn't Know About Firebase Auth
6 Things You Didn't Know About Firebase Auth
 
Five Things You Didn't Know About Firebase Auth
Five Things You Didn't Know About Firebase AuthFive Things You Didn't Know About Firebase Auth
Five Things You Didn't Know About Firebase Auth
 
Building High-Quality Apps for Google Assistant
Building High-Quality Apps for Google AssistantBuilding High-Quality Apps for Google Assistant
Building High-Quality Apps for Google Assistant
 
Building Conversational Experiences with Actions on Google
Building Conversational Experiences with Actions on Google Building Conversational Experiences with Actions on Google
Building Conversational Experiences with Actions on Google
 
Building Conversational Experiences with Actions on Google
Building Conversational Experiences with Actions on GoogleBuilding Conversational Experiences with Actions on Google
Building Conversational Experiences with Actions on Google
 
What's new in Android Wear 2.0
What's new in Android Wear 2.0What's new in Android Wear 2.0
What's new in Android Wear 2.0
 
Google Fit, Android Wear & Xamarin
Google Fit, Android Wear & XamarinGoogle Fit, Android Wear & Xamarin
Google Fit, Android Wear & Xamarin
 
Introduction to Android Wear
Introduction to Android WearIntroduction to Android Wear
Introduction to Android Wear
 
Google Play Services Rock
Google Play Services RockGoogle Play Services Rock
Google Play Services Rock
 
Introduction to Android Wear
Introduction to Android WearIntroduction to Android Wear
Introduction to Android Wear
 
Google+ for Mobile Apps on iOS and Android
Google+ for Mobile Apps on iOS and AndroidGoogle+ for Mobile Apps on iOS and Android
Google+ for Mobile Apps on iOS and Android
 
Cross-Platform Authentication with Google+ Sign-In
Cross-Platform Authentication with Google+ Sign-InCross-Platform Authentication with Google+ Sign-In
Cross-Platform Authentication with Google+ Sign-In
 
Bring Back the Fun to Testing Android Apps with Robolectric
Bring Back the Fun to Testing Android Apps with RobolectricBring Back the Fun to Testing Android Apps with Robolectric
Bring Back the Fun to Testing Android Apps with Robolectric
 

Kürzlich hochgeladen

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 

Rapid Application Development with SwiftUI and Firebase

  • 1. Rapid Application Development with SwiftUI and Firebase Peter Friese, Developer Advocate, Google @peterfriese 🔥
  • 2.
  • 3. Demo 1 Kaffeinated - A coffee tracking app
  • 4.
  • 5.
  • 6. SwiftUI • A declarative way to build your UI • Everything is a view • Every SwiftUI view is a struct • You build UIs by composing views • Views are a function of their state Better state management!
  • 7. struct ContentView: View { var body: some View { Text("Hello, World!") } } SwiftUI Views
  • 8. Demo 2 Building a List From Scratch
  • 9.
  • 10.
  • 11.
  • 12. Improve app quality Crashlytics Performance Monitoring Test Lab App Distribution Grow your app Analytics Predictions Cloud Messaging Remote Config A/B Testing Dynamic Links In-app Messaging Build better apps Auth Cloud Functions Cloud Firestore Hosting ML Kit Realtime Database Cloud Storage bit.ly/what-is-firebase
  • 13.
  • 14. Mobile Databases - The Hard Way Database MongoDB, Postgres, MySQL, etc API Server REST API on top of database Auth Service Protects the API server Sync Logic REST API calls, caches, etc SQLite Store data offline
  • 15. Cross-platform? You're going to have to write the same code multiple times!
  • 17.
  • 21. collection("restaurants"). where("city", " ==", "Cairo"). orderBy(“rating”, "desc").limit(10) Here ya go!
  • 22. Add Firebase to Your iOS Project 1. Create a new Firebase project 2. Register your iOS app 3. Download configuration file 4. Install the Firebase Cocoapod 5. Call FirebaseApp.configure()
  • 24. Fetching Data from Firestore
  • 25. db.collection("coffees").addSnapshotListener { (querySnapshot, error) in var coffees = [Coffee]() querySnapshot ?.documents.forEach { document in let coffeeName = document.data()["name"] as? String ?? "" let shortDescription = document.data()["shortDescription"] as? String ?? "" let description = document.data()["description"] as? String ?? "" let caffeineAmount = document.data()["caffeineAmount"] as? Int ?? 0 let coffee = Coffee(name: coffeeName, shortDescription: shortDescription, description: description, caffeineAmount: caffeineAmount) coffees.append(coffee) } self.coffees = coffees } Fetching Data from Firestore
  • 26.
  • 27. Firestore & Codable • One of our most-requested and longest-running feature requests • Released on October 22nd, 2019 • Makes fetching and writing much easier
  • 28. db.collection("coffees").addSnapshotListener { (querySnapshot, error) in var coffees = [Coffee]() querySnapshot ?.documents.forEach { document in let coffeeName = document.data()["name"] as? String ?? "" let shortDescription = document.data()["shortDescription"] as? String ?? "" let description = document.data()["description"] as? String ?? "" let caffeineAmount = document.data()["caffeineAmount"] as? Int ?? 0 let coffee = Coffee(name: coffeeName, shortDescription: shortDescription, description: description, caffeineAmount: caffeineAmount) coffees.append(coffee) } self.coffees = coffees } Fetching Data - w/o Codable
  • 29. // Model struct Coffee: Codable, Identifiable { @DocumentID var id: String? var name: String var shortDescription: String var description: String } // Elsewhere, fetch our data: db.collection("coffees").addSnapshotListener { (querySnapshot, error) in if let querySnapshot = querySnapshot { self.coffees = querySnapshot.documents.compactMap { document -> Coffee? in try? document.data(as: Coffee.self) } } } Fetching Data - w/ Codable
  • 30. Saving Data to Firestore
  • 31. let db = Firestore.firestore() do { _ = try db.collection(“users/(user.uid)/consumption/") .addDocument(from: consumption) } catch { print(“Error: (error.localizedDescription).") } Saving Data to Firestore
  • 32. let db = Firestore.firestore() do { _ = try db.collection(“users/(user.uid)/consumption/") .addDocument(from: consumption) } catch { print(“Error: (error.localizedDescription).") } Saving Data to Firestore We didn’t sign in, so what’s this kind of magic?
  • 34. Auth.auth().signInAnonymously() { (authResult, error) in guard let user = authResult ?.user else { return } let isAnonymous = user.isAnonymous // true let uid = user.uid } Anonymous Auth
  • 35. let db = Firestore.firestore() do { _ = try db.collection(“users/(user.uid)/consumption/") .addDocument(from: consumption) } catch { print(“Error: (error.localizedDescription).") } Saving Data to Firestore
  • 37. Data Flow • Property • @State • @Binding • @ObservedObject • @EnvironmentObject • Sarah Reichelt: SwiftUI Data Flow (bit.ly/SwiftUIDataFlow)
  • 38. struct BarsView: View { let bars: [Bar] let max: Double init(bars: [Bar]) { self.bars = bars self.max = bars.map { $0.value }.max() ?? 0 } var body: some View { GeometryReader { geometry in HStack(alignment: .bottom, spacing: 0) { ForEach(self.bars) { bar in Rectangle() .fill(bar.color) .frame(width: 10, height: CGFloat(bar.value) / CGFloat(self.max) * geometry.size.height) Data Flow - Property
  • 39. struct MainView: View { @State var selectedTab = 0 @EnvironmentObject var appState: AppState var body: some View { TabView(selection: $selectedTab) { } } } Data Flow - @State
  • 40. class CoffeeListViewModel: ObservableObject { @Published var coffees: [Coffee] } struct CoffeeListView: View { @ObservedObject var viewModel: CoffeeListViewModel var body: some View { NavigationView { List(viewModel.coffees) { coffee in CoffeeCell(coffee: coffee) } .navigationBarTitle("Coffees") } } } Data Flow - @ObservableObject
  • 41. class AppState: ObservableObject { @Published var coffees = [Coffee]() @Published var consumptions = [Consumption]() } let appState = AppState() let contentView = MainView() window.rootViewController = UIHostingController(rootView: contentView.environmentObject(appState)) struct MainView: View { @EnvironmentObject var appState: AppState var body: some View { HistoryView(viewModel: HistoryViewModel(consumption: appState.consumptions)) .tabItem { Image(systemName: “chart.bar.fill”)) } } } Data Flow - @EnvironmentObject
  • 42. Data Flow for Firebase Apps MainViewAppState [Coffee] [Consumption] User ... Environment CoffeeListView CoffeeListVM [Coffee] Firestore
  • 43. Demo 3 The Final App, Using Firebase
  • 44.
  • 45.
  • 47. Conclusion • Achieve great results in a short amount of time • Documentation a bit lacking • Great contributions from the community • A number of things don’t work (yet) • Fill the gaps with UIViewControllerRepresentable
  • 48. Conclusion • Work together well • No critical issues so far • Firebase team eager to hear from the community +
  • 49.
  • 50. Thanks! Peter Friese, Developer Advocate, Google @peterfriese https://peterfriese.dev https://medium.com/@peterfriese https://medium.com/firebase-developers