diff --git a/.github/workflows/appcheck.yml b/.github/workflows/appcheck.yml new file mode 100644 index 00000000..38c18362 --- /dev/null +++ b/.github/workflows/appcheck.yml @@ -0,0 +1,37 @@ +on: + pull_request: + paths: + - 'appcheck/**' + - '.github/workflows/appcheck.yml' +name: App Check +jobs: + swift-build: + name: Swift build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build Swift snippets + run: | + cd appcheck + xcodebuild -project AppCheckSnippets.xcodeproj clean build -scheme AppCheckSnippetsSwift -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} + objc-build: + name: ObjC build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build ObjC snippets + run: | + cd appcheck + xcodebuild -project AppCheckSnippets.xcodeproj clean build -scheme AppCheckSnippetsObjC -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} diff --git a/.github/workflows/core.yml b/.github/workflows/core.yml index f32d8aba..8c13cb59 100644 --- a/.github/workflows/core.yml +++ b/.github/workflows/core.yml @@ -10,7 +10,7 @@ jobs: runs-on: macOS-latest strategy: matrix: - destination: ['platform=iOS Simulator,OS=latest,name=iPhone 11'] + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] steps: - name: Checkout uses: actions/checkout@master @@ -18,7 +18,6 @@ jobs: run: | cp .github/GoogleService-Info-CI.plist firoptions/FiroptionConfiguration/GoogleService-Info.plist cd firoptions - pod install --repo-update - xcodebuild -workspace FiroptionConfiguration.xcworkspace clean build -scheme FiroptionConfiguration -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + xcodebuild -project FiroptionConfiguration.xcodeproj clean build -scheme FiroptionConfiguration -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO env: destination: ${{ matrix.destination }} diff --git a/.github/workflows/crashlytics.yml b/.github/workflows/crashlytics.yml new file mode 100644 index 00000000..2cf9ea47 --- /dev/null +++ b/.github/workflows/crashlytics.yml @@ -0,0 +1,37 @@ +on: + pull_request: + paths: + - 'crashlytics/**' + - '.github/workflows/crashlytics.yml' +name: Crashlytics +jobs: + swift-build: + name: Swift build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build Swift snippets + run: | + cd crashlytics + xcodebuild -project CrashlyticsExample.xcodeproj clean build -scheme CrashlyticsExampleSwift -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} + objc-build: + name: ObjC build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build ObjC snippets + run: | + cd crashlytics + xcodebuild -project CrashlyticsExample.xcodeproj clean build -scheme CrashlyticsExample -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml new file mode 100644 index 00000000..2f6b2306 --- /dev/null +++ b/.github/workflows/database.yml @@ -0,0 +1,22 @@ +on: + pull_request: + paths: + - 'database/**' + - '.github/workflows/database.yml' +name: Database +jobs: + swift-build: + name: Build combined snippets + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build snippets + run: | + cd database + xcodebuild -project DatabaseReference.xcodeproj clean build -scheme DatabaseReference -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} diff --git a/.github/workflows/firestore.yml b/.github/workflows/firestore.yml index 30b3e1ed..bfcc6798 100644 --- a/.github/workflows/firestore.yml +++ b/.github/workflows/firestore.yml @@ -10,7 +10,7 @@ jobs: runs-on: macOS-latest strategy: matrix: - destination: ['platform=iOS Simulator,OS=latest,name=iPhone 11'] + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] steps: - name: Checkout uses: actions/checkout@master @@ -18,8 +18,7 @@ jobs: run: | cp .github/GoogleService-Info-CI.plist firestore/swift/firestore-smoketest/GoogleService-Info.plist cd firestore/swift - pod install --repo-update - xcodebuild -workspace firestore-smoketest.xcworkspace clean build -scheme firestore-smoketest -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + xcodebuild -project firestore-smoketest.xcodeproj clean build -scheme firestore-smoketest -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO env: destination: ${{ matrix.destination }} objc-build: @@ -27,7 +26,7 @@ jobs: runs-on: macOS-latest strategy: matrix: - destination: ['platform=iOS Simulator,OS=latest,name=iPhone 11'] + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] steps: - name: Checkout uses: actions/checkout@master @@ -35,7 +34,6 @@ jobs: run: | cp .github/GoogleService-Info-CI.plist firestore/objc/GoogleService-Info.plist cd firestore/objc - pod install --repo-update - xcodebuild -workspace firestore-smoketest-objc.xcworkspace clean build -scheme firestore-smoketest-objc -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + xcodebuild -project firestore-smoketest-objc.xcodeproj clean build -scheme firestore-smoketest-objc -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO env: destination: ${{ matrix.destination }} diff --git a/.github/workflows/functions.yml b/.github/workflows/functions.yml new file mode 100644 index 00000000..61bca69e --- /dev/null +++ b/.github/workflows/functions.yml @@ -0,0 +1,37 @@ +on: + pull_request: + paths: + - 'functions/**' + - '.github/workflows/functions.yml' +name: Functions +jobs: + swift-build: + name: Swift build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build Swift snippets + run: | + cd functions + xcodebuild -project FunctionsExample.xcodeproj clean build -scheme FunctionsExampleSwift -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} + objc-build: + name: ObjC build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build ObjC snippets + run: | + cd functions + xcodebuild -project FunctionsExample.xcodeproj clean build -scheme FunctionsExample -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} diff --git a/.github/workflows/installations.yml b/.github/workflows/installations.yml index 368fd7a8..1583f142 100644 --- a/.github/workflows/installations.yml +++ b/.github/workflows/installations.yml @@ -10,14 +10,13 @@ jobs: runs-on: macOS-latest strategy: matrix: - destination: ['platform=iOS Simulator,OS=latest,name=iPhone 11'] + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] steps: - name: Checkout uses: actions/checkout@master - name: Build Swift snippets run: | cd installations/ - pod install --repo-update - xcodebuild -workspace InstallationsSnippets.xcworkspace clean build -scheme InstallationsSnippets -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + xcodebuild -project InstallationsSnippets.xcodeproj clean build -scheme InstallationsSnippets -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO env: destination: ${{ matrix.destination }} \ No newline at end of file diff --git a/.github/workflows/ml-functions.yml b/.github/workflows/ml-functions.yml new file mode 100644 index 00000000..4fb478db --- /dev/null +++ b/.github/workflows/ml-functions.yml @@ -0,0 +1,37 @@ +on: + pull_request: + paths: + - 'ml-functions/**' + - '.github/workflows/ml-functions.yml' +name: Functions (ML) +jobs: + swift-build: + name: Swift build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build Swift snippets + run: | + cd ml-functions + xcodebuild -project MLFunctionsExample.xcodeproj clean build -scheme MLFunctionsExampleSwift -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} + objc-build: + name: ObjC build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build ObjC snippets + run: | + cd ml-functions + xcodebuild -project MLFunctionsExample.xcodeproj clean build -scheme MLFunctionsExample -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} diff --git a/.github/workflows/storage.yml b/.github/workflows/storage.yml new file mode 100644 index 00000000..28416620 --- /dev/null +++ b/.github/workflows/storage.yml @@ -0,0 +1,39 @@ +on: + pull_request: + paths: + - 'storage/**' + - '.github/workflows/storage.yml' +name: Storage +jobs: + swift-build: + name: Swift build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build Swift snippets + run: | + sudo xcode-select -switch /Applications/Xcode_16.1.app/Contents/Developer + cd storage + xcodebuild -project StorageReference.xcodeproj clean build -scheme StorageReferenceSwift -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} + objc-build: + name: ObjC build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 16'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build ObjC snippets + run: | + sudo xcode-select -switch /Applications/Xcode_16.1.app/Contents/Developer + cd storage + xcodebuild -project StorageReference.xcodeproj clean build -scheme StorageReference -destination "${destination}" CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} diff --git a/.github/workflows/vertexai.yml b/.github/workflows/vertexai.yml new file mode 100644 index 00000000..f5757908 --- /dev/null +++ b/.github/workflows/vertexai.yml @@ -0,0 +1,22 @@ +on: + pull_request: + paths: + - 'vertexai/**' + - '.github/workflows/vertexai.yml' +name: VertexAI +jobs: + snippets-build: + name: snippets build + runs-on: macOS-latest + strategy: + matrix: + destination: ['platform=iOS Simulator,OS=latest,name=iPhone 15', 'platform=OS X'] + steps: + - name: Checkout + uses: actions/checkout@master + - name: Build Swift snippets + run: | + cd vertexai + xcodebuild -project VertexAISnippets.xcodeproj -scheme VertexAISnippets clean build -destination "${destination}" CODE_SIGNING_REQUIRED=NO + env: + destination: ${{ matrix.destination }} diff --git a/appcheck/AppCheckSnippets.xcodeproj/project.pbxproj b/appcheck/AppCheckSnippets.xcodeproj/project.pbxproj index 0322fab4..319930a4 100644 --- a/appcheck/AppCheckSnippets.xcodeproj/project.pbxproj +++ b/appcheck/AppCheckSnippets.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -24,6 +24,10 @@ 4265C3BC26AF775A00BD1DB2 /* AppAttestProviderFactories.m in Sources */ = {isa = PBXBuildFile; fileRef = 4265C3BB26AF775A00BD1DB2 /* AppAttestProviderFactories.m */; }; 4265C3BE26AF7A6600BD1DB2 /* YourCustomAppCheckProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4265C3BD26AF7A6600BD1DB2 /* YourCustomAppCheckProvider.swift */; }; 4265C3C026AF7A7E00BD1DB2 /* YourCustomAppCheckProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 4265C3BF26AF7A7E00BD1DB2 /* YourCustomAppCheckProvider.m */; }; + 8D7726082D2874A100537A0B /* FirebaseAppCheck in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7726072D2874A100537A0B /* FirebaseAppCheck */; }; + 8D77260A2D2874A100537A0B /* FirebaseCore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7726092D2874A100537A0B /* FirebaseCore */; }; + 8D77260D2D2874BA00537A0B /* FirebaseAppCheck in Frameworks */ = {isa = PBXBuildFile; productRef = 8D77260C2D2874BA00537A0B /* FirebaseAppCheck */; }; + 8D77260F2D2874BA00537A0B /* FirebaseCore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D77260E2D2874BA00537A0B /* FirebaseCore */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -58,6 +62,8 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D77260A2D2874A100537A0B /* FirebaseCore in Frameworks */, + 8D7726082D2874A100537A0B /* FirebaseAppCheck in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -65,19 +71,14 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D77260F2D2874BA00537A0B /* FirebaseCore in Frameworks */, + 8D77260D2D2874BA00537A0B /* FirebaseAppCheck in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 37860BEBF061B43F7FE74ABB /* Pods */ = { - isa = PBXGroup; - children = ( - ); - path = Pods; - sourceTree = ""; - }; 4265C38826AF71E100BD1DB2 /* Products */ = { isa = PBXGroup; children = ( @@ -128,11 +129,18 @@ children = ( 4265C38926AF71E100BD1DB2 /* AppCheckSnippetsObjC */, 4265C3A626AF723800BD1DB2 /* AppCheckSnippetsSwift */, + 8D77260B2D2874BA00537A0B /* Frameworks */, 4265C38826AF71E100BD1DB2 /* Products */, - 37860BEBF061B43F7FE74ABB /* Pods */, ); sourceTree = ""; }; + 8D77260B2D2874BA00537A0B /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -196,6 +204,9 @@ Base, ); mainGroup = 42A83E6D26AF6E5C00097CA3; + packageReferences = ( + 8D7726062D2874A100537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 4265C38826AF71E100BD1DB2 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -610,6 +621,40 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7726062D2874A100537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7726072D2874A100537A0B /* FirebaseAppCheck */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726062D2874A100537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAppCheck; + }; + 8D7726092D2874A100537A0B /* FirebaseCore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726062D2874A100537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCore; + }; + 8D77260C2D2874BA00537A0B /* FirebaseAppCheck */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726062D2874A100537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAppCheck; + }; + 8D77260E2D2874BA00537A0B /* FirebaseCore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726062D2874A100537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCore; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 42A83E6E26AF6E5C00097CA3 /* Project object */; } diff --git a/appcheck/AppCheckSnippetsObjC/AppDelegate.m b/appcheck/AppCheckSnippetsObjC/AppDelegate.m index 3638f6f7..2bf07506 100644 --- a/appcheck/AppCheckSnippetsObjC/AppDelegate.m +++ b/appcheck/AppCheckSnippetsObjC/AppDelegate.m @@ -15,6 +15,7 @@ // #import "AppDelegate.h" +@import FirebaseCore; @import FirebaseAppCheck; @interface AppDelegate () diff --git a/appcheck/AppCheckSnippetsSwift/AppAttestProviderFactories.swift b/appcheck/AppCheckSnippetsSwift/AppAttestProviderFactories.swift index d11c32d5..cb209737 100644 --- a/appcheck/AppCheckSnippetsSwift/AppAttestProviderFactories.swift +++ b/appcheck/AppCheckSnippetsSwift/AppAttestProviderFactories.swift @@ -14,6 +14,7 @@ // limitations under the License. // +import FirebaseCore import FirebaseAppCheck // [START appcheck_simple_appattest_factory] diff --git a/appcheck/AppCheckSnippetsSwift/AppDelegate.swift b/appcheck/AppCheckSnippetsSwift/AppDelegate.swift index dd6c8da9..5ea067fc 100644 --- a/appcheck/AppCheckSnippetsSwift/AppDelegate.swift +++ b/appcheck/AppCheckSnippetsSwift/AppDelegate.swift @@ -15,77 +15,65 @@ // import UIKit +import FirebaseCore import FirebaseAppCheck @main class AppDelegate: UIResponder, UIApplicationDelegate { - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - return true - } - - func initCustom() { - // [START appcheck_initialize_custom] - let providerFactory = YourAppCheckProviderFactory() - AppCheck.setAppCheckProviderFactory(providerFactory) + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + return true + } - FirebaseApp.configure() - // [END appcheck_initialize_custom] - } - - func initDebug() { - // [START appcheck_initialize_debug] - let providerFactory = AppCheckDebugProviderFactory() - AppCheck.setAppCheckProviderFactory(providerFactory) + func initCustom() { + // [START appcheck_initialize_custom] + let providerFactory = YourAppCheckProviderFactory() + AppCheck.setAppCheckProviderFactory(providerFactory) - FirebaseApp.configure() - // [END appcheck_initialize_debug] - } - - func nonFirebaseBackend() { - // [START appcheck_nonfirebase] - AppCheck.appCheck().token(forcingRefresh: false) { token, error in - guard error == nil else { - // Handle any errors if the token was not retrieved. - print("Unable to retrieve App Check token: \(error!)") - return - } - guard let token = token else { - print("Unable to retrieve App Check token.") - return - } + FirebaseApp.configure() + // [END appcheck_initialize_custom] + } - // Get the raw App Check token string. - let tokenString = token.token + func initDebug() { + // [START appcheck_initialize_debug] + let providerFactory = AppCheckDebugProviderFactory() + AppCheck.setAppCheckProviderFactory(providerFactory) - // Include the App Check token with requests to your server. - let url = URL(string: "https://yourbackend.example.com/yourApiEndpoint")! - var request = URLRequest(url: url) - request.httpMethod = "GET" - request.setValue(tokenString, forHTTPHeaderField: "X-Firebase-AppCheck") + FirebaseApp.configure() + // [END appcheck_initialize_debug] + } - let task = URLSession.shared.dataTask(with: request) { data, response, error in - // Handle response from your backend. - } - task.resume() - } - // [END appcheck_nonfirebase] - } + func nonFirebaseBackend() async { + // [START appcheck_nonfirebase] + + do { + let token = try await AppCheck.appCheck().token(forcingRefresh: false) - // MARK: UISceneSession Lifecycle + // Get the raw App Check token string. + let tokenString = token.token - func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { - // Called when a new scene session is being created. - // Use this method to select a configuration to create the new scene with. - return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) - } + // Include the App Check token with requests to your server. + let url = URL(string: "https://yourbackend.example.com/yourApiEndpoint")! + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.setValue(tokenString, forHTTPHeaderField: "X-Firebase-AppCheck") - func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + let task = URLSession.shared.dataTask(with: request) { data, response, error in + // Handle response from your backend. + } + task.resume() + } catch(let error) { + print("Unable to retrieve App Check token: \(error)") + return } + // [END appcheck_nonfirebase] + } + + // MARK: UISceneSession Lifecycle + func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { + return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + } } diff --git a/appcheck/AppCheckSnippetsSwift/YourCustomAppCheckProvider.swift b/appcheck/AppCheckSnippetsSwift/YourCustomAppCheckProvider.swift index d2e03e53..ae4971cc 100644 --- a/appcheck/AppCheckSnippetsSwift/YourCustomAppCheckProvider.swift +++ b/appcheck/AppCheckSnippetsSwift/YourCustomAppCheckProvider.swift @@ -14,36 +14,42 @@ // limitations under the License. // +import FirebaseCore import FirebaseAppCheck // [START appcheck_custom_provider] class YourCustomAppCheckProvider: NSObject, AppCheckProvider { - var app: FirebaseApp + var app: FirebaseApp - init(withFirebaseApp app: FirebaseApp) { - self.app = app - super.init() - } + init(withFirebaseApp app: FirebaseApp) { + self.app = app + super.init() + } + + func getToken() async throws -> AppCheckToken { + let getTokenTask = Task { () -> AppCheckToken in + // [START_EXCLUDE] + let expirationFromServer = 1000.0 + let tokenFromServer = "token" + // [END_EXCLUDE] + + // Create AppCheckToken object. + let exp = Date(timeIntervalSince1970: expirationFromServer) + let token = AppCheckToken( + token: tokenFromServer, + expirationDate: exp + ) - func getToken(completion handler: @escaping (AppCheckToken?, Error?) -> Void) { - DispatchQueue.main.async { - // Logic to exchange proof of authenticity for an App Check token. - // [START_EXCLUDE] - let expirationFromServer = 1000.0 - let tokenFromServer = "token" - // [END_EXCLUDE] - - // Create AppCheckToken object. - let exp = Date(timeIntervalSince1970: expirationFromServer) - let token = AppCheckToken( - token: tokenFromServer, - expirationDate: exp - ) - - // Pass the token or error to the completion handler. - handler(token, nil) - } + if Date() > exp { + throw NSError(domain: "ExampleError", code: 1, userInfo: nil) + } + + return token } + + return try await getTokenTask.value + } + } // [END appcheck_custom_provider] diff --git a/appcheck/Podfile b/appcheck/Podfile deleted file mode 100644 index 17e30745..00000000 --- a/appcheck/Podfile +++ /dev/null @@ -1,20 +0,0 @@ -# Uncomment the next line to define a global platform for your project -platform :ios, '14.0' - -target 'AppCheckSnippetsObjC' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - # Pods for AppCheckSnippetsObjC - pod 'Firebase/AppCheck' - -end - -target 'AppCheckSnippetsSwift' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - # Pods for AppCheckSnippetsSwift - pod 'Firebase/AppCheck' - -end diff --git a/appcheck/Podfile.lock b/appcheck/Podfile.lock deleted file mode 100644 index 7c6453ec..00000000 --- a/appcheck/Podfile.lock +++ /dev/null @@ -1,46 +0,0 @@ -PODS: - - Firebase/AppCheck (10.2.0): - - Firebase/CoreOnly - - FirebaseAppCheck (~> 10.2.0) - - Firebase/CoreOnly (10.2.0): - - FirebaseCore (= 10.2.0) - - FirebaseAppCheck (10.2.0): - - FirebaseCore (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - PromisesObjC (~> 2.1) - - FirebaseCore (10.2.0): - - FirebaseCoreInternal (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/Logger (~> 7.8) - - FirebaseCoreInternal (10.2.0): - - "GoogleUtilities/NSData+zlib (~> 7.8)" - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - "GoogleUtilities/NSData+zlib (7.10.0)" - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - Firebase/AppCheck - -SPEC REPOS: - trunk: - - Firebase - - FirebaseAppCheck - - FirebaseCore - - FirebaseCoreInternal - - GoogleUtilities - - PromisesObjC - -SPEC CHECKSUMS: - Firebase: a3ea7eba4382afd83808376edb99acdaff078dcf - FirebaseAppCheck: 17e885f852bcba290b18c29a2718e3d48c571833 - FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1 - FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 3f5fe9faa57008d6327228db502ed5519ccd4918 - -COCOAPODS: 1.11.3 diff --git a/crashlytics/CrashlyticsExample.xcodeproj/project.pbxproj b/crashlytics/CrashlyticsExample.xcodeproj/project.pbxproj index 8bda94e4..7c014915 100644 --- a/crashlytics/CrashlyticsExample.xcodeproj/project.pbxproj +++ b/crashlytics/CrashlyticsExample.xcodeproj/project.pbxproj @@ -3,10 +3,14 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ + 8D7726132D2876F400537A0B /* FirebaseCore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7726122D2876F400537A0B /* FirebaseCore */; }; + 8D7726152D2876F400537A0B /* FirebaseCrashlytics in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7726142D2876F400537A0B /* FirebaseCrashlytics */; }; + 8D7726172D2876FB00537A0B /* FirebaseCore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7726162D2876FB00537A0B /* FirebaseCore */; }; + 8D7726192D2876FB00537A0B /* FirebaseCrashlytics in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7726182D2876FB00537A0B /* FirebaseCrashlytics */; }; 8D8FA34322F4CAB100213E06 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D8FA34222F4CAB100213E06 /* AppDelegate.m */; }; 8D8FA34622F4CAB100213E06 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D8FA34522F4CAB100213E06 /* ViewController.m */; }; 8D8FA34922F4CAB100213E06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D8FA34722F4CAB100213E06 /* Main.storyboard */; }; @@ -45,6 +49,8 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7726132D2876F400537A0B /* FirebaseCore in Frameworks */, + 8D7726152D2876F400537A0B /* FirebaseCrashlytics in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -52,19 +58,28 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7726172D2876FB00537A0B /* FirebaseCore in Frameworks */, + 8D7726192D2876FB00537A0B /* FirebaseCrashlytics in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 8D7726112D2876F400537A0B /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; 8D8FA33522F4CAB100213E06 = { isa = PBXGroup; children = ( 8D8FA34022F4CAB100213E06 /* CrashlyticsExample */, 8D8FA35C22F4CAF700213E06 /* CrashlyticsExampleSwift */, + 8D7726112D2876F400537A0B /* Frameworks */, 8D8FA33F22F4CAB100213E06 /* Products */, - E21099940C3416ACBB0EB9EC /* Pods */, ); sourceTree = ""; }; @@ -106,13 +121,6 @@ path = CrashlyticsExampleSwift; sourceTree = ""; }; - E21099940C3416ACBB0EB9EC /* Pods */ = { - isa = PBXGroup; - children = ( - ); - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -177,6 +185,9 @@ Base, ); mainGroup = 8D8FA33522F4CAB100213E06; + packageReferences = ( + 8D7726102D2876EB00537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 8D8FA33F22F4CAB100213E06 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -484,6 +495,40 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7726102D2876EB00537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7726122D2876F400537A0B /* FirebaseCore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726102D2876EB00537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCore; + }; + 8D7726142D2876F400537A0B /* FirebaseCrashlytics */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726102D2876EB00537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCrashlytics; + }; + 8D7726162D2876FB00537A0B /* FirebaseCore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726102D2876EB00537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCore; + }; + 8D7726182D2876FB00537A0B /* FirebaseCrashlytics */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7726102D2876EB00537A0B /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCrashlytics; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 8D8FA33622F4CAB100213E06 /* Project object */; } diff --git a/crashlytics/Podfile b/crashlytics/Podfile deleted file mode 100644 index 367b5dd1..00000000 --- a/crashlytics/Podfile +++ /dev/null @@ -1,18 +0,0 @@ -# Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' - -target 'CrashlyticsExample' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - pod 'Firebase/Crashlytics' - -end - -target 'CrashlyticsExampleSwift' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - pod 'Firebase/Crashlytics' - -end diff --git a/crashlytics/Podfile.lock b/crashlytics/Podfile.lock deleted file mode 100644 index 7f5c6afb..00000000 --- a/crashlytics/Podfile.lock +++ /dev/null @@ -1,71 +0,0 @@ -PODS: - - Firebase/CoreOnly (10.2.0): - - FirebaseCore (= 10.2.0) - - Firebase/Crashlytics (10.2.0): - - Firebase/CoreOnly - - FirebaseCrashlytics (~> 10.2.0) - - FirebaseCore (10.2.0): - - FirebaseCoreInternal (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/Logger (~> 7.8) - - FirebaseCoreInternal (10.2.0): - - "GoogleUtilities/NSData+zlib (~> 7.8)" - - FirebaseCrashlytics (10.2.0): - - FirebaseCore (~> 10.0) - - FirebaseInstallations (~> 10.0) - - GoogleDataTransport (~> 9.2) - - GoogleUtilities/Environment (~> 7.8) - - nanopb (< 2.30910.0, >= 2.30908.0) - - PromisesObjC (~> 2.1) - - FirebaseInstallations (10.2.0): - - FirebaseCore (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/UserDefaults (~> 7.8) - - PromisesObjC (~> 2.1) - - GoogleDataTransport (9.2.0): - - GoogleUtilities/Environment (~> 7.7) - - nanopb (< 2.30910.0, >= 2.30908.0) - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GoogleUtilities/UserDefaults (7.10.0): - - GoogleUtilities/Logger - - nanopb (2.30909.0): - - nanopb/decode (= 2.30909.0) - - nanopb/encode (= 2.30909.0) - - nanopb/decode (2.30909.0) - - nanopb/encode (2.30909.0) - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - Firebase/Crashlytics - -SPEC REPOS: - trunk: - - Firebase - - FirebaseCore - - FirebaseCoreInternal - - FirebaseCrashlytics - - FirebaseInstallations - - GoogleDataTransport - - GoogleUtilities - - nanopb - - PromisesObjC - -SPEC CHECKSUMS: - Firebase: a3ea7eba4382afd83808376edb99acdaff078dcf - FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1 - FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f - FirebaseCrashlytics: df7406152189d48346deafb716806d7bd9ebb573 - FirebaseInstallations: 004915af170935e3a583faefd5f8bc851afc220f - GoogleDataTransport: 1c8145da7117bd68bbbed00cf304edb6a24de00f - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 7d7fc01886b20bf15f0faadc1d61966683471571 - -COCOAPODS: 1.11.3 diff --git a/database/swift.xcodeproj/project.pbxproj b/database/DatabaseReference.xcodeproj/project.pbxproj similarity index 86% rename from database/swift.xcodeproj/project.pbxproj rename to database/DatabaseReference.xcodeproj/project.pbxproj index 86e32aa9..f4c85ed6 100644 --- a/database/swift.xcodeproj/project.pbxproj +++ b/database/DatabaseReference.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -11,6 +11,8 @@ 8D19B3751EA7D49400451CA7 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D19B3731EA7D49400451CA7 /* ViewController.m */; }; 8D19B3781EA7D4A300451CA7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D19B3761EA7D4A300451CA7 /* AppDelegate.swift */; }; 8D19B3791EA7D4A300451CA7 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D19B3771EA7D4A300451CA7 /* ViewController.swift */; }; + 8D474FD62D28A9CF000B5C38 /* FirebaseAuth in Frameworks */ = {isa = PBXBuildFile; productRef = 8D474FD52D28A9CF000B5C38 /* FirebaseAuth */; }; + 8D474FD82D28A9CF000B5C38 /* FirebaseDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = 8D474FD72D28A9CF000B5C38 /* FirebaseDatabase */; }; 8DDD574C1EA6D39D00DD14EB /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8DDD574A1EA6D39D00DD14EB /* Main.storyboard */; }; 8DDD574E1EA6D39D00DD14EB /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8DDD574D1EA6D39D00DD14EB /* Assets.xcassets */; }; 8DDD57511EA6D39D00DD14EB /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8DDD574F1EA6D39D00DD14EB /* LaunchScreen.storyboard */; }; @@ -35,12 +37,21 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D474FD82D28A9CF000B5C38 /* FirebaseDatabase in Frameworks */, + 8D474FD62D28A9CF000B5C38 /* FirebaseAuth in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 8D474FD42D28A9CF000B5C38 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; 8D5CA1551EA6D5490024095C /* ObjC */ = { isa = PBXGroup; children = ( @@ -65,8 +76,8 @@ isa = PBXGroup; children = ( 8DDD57451EA6D39D00DD14EB /* DatabaseReference */, + 8D474FD42D28A9CF000B5C38 /* Frameworks */, 8DDD57441EA6D39D00DD14EB /* Products */, - D8F966BF59E6A1509FCBF383 /* Pods */, ); sourceTree = ""; }; @@ -91,13 +102,6 @@ path = DatabaseReference; sourceTree = ""; }; - D8F966BF59E6A1509FCBF383 /* Pods */ = { - isa = PBXGroup; - children = ( - ); - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -135,7 +139,7 @@ }; }; }; - buildConfigurationList = 8DDD573E1EA6D39D00DD14EB /* Build configuration list for PBXProject "swift" */; + buildConfigurationList = 8DDD573E1EA6D39D00DD14EB /* Build configuration list for PBXProject "DatabaseReference" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; @@ -145,6 +149,9 @@ Base, ); mainGroup = 8DDD573A1EA6D39D00DD14EB; + packageReferences = ( + 8D474FD32D28A9C3000B5C38 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 8DDD57441EA6D39D00DD14EB /* Products */; projectDirPath = ""; projectRoot = ""; @@ -291,7 +298,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; @@ -304,7 +312,11 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = DatabaseReference/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.referencecode.DatabaseReference; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = ""; @@ -319,7 +331,11 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = DatabaseReference/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.referencecode.DatabaseReference; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = ""; @@ -330,7 +346,7 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 8DDD573E1EA6D39D00DD14EB /* Build configuration list for PBXProject "swift" */ = { + 8DDD573E1EA6D39D00DD14EB /* Build configuration list for PBXProject "DatabaseReference" */ = { isa = XCConfigurationList; buildConfigurations = ( 8DDD575E1EA6D39D00DD14EB /* Debug */, @@ -349,6 +365,30 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D474FD32D28A9C3000B5C38 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D474FD52D28A9CF000B5C38 /* FirebaseAuth */ = { + isa = XCSwiftPackageProductDependency; + package = 8D474FD32D28A9C3000B5C38 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAuth; + }; + 8D474FD72D28A9CF000B5C38 /* FirebaseDatabase */ = { + isa = XCSwiftPackageProductDependency; + package = 8D474FD32D28A9C3000B5C38 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseDatabase; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 8DDD573B1EA6D39D00DD14EB /* Project object */; } diff --git a/database/DatabaseReference.xcworkspace/contents.xcworkspacedata b/database/DatabaseReference.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index b4e48b12..00000000 --- a/database/DatabaseReference.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/database/DatabaseReference/objc/AppDelegate.m b/database/DatabaseReference/objc/AppDelegate.m index aeacb86e..91461ffc 100644 --- a/database/DatabaseReference/objc/AppDelegate.m +++ b/database/DatabaseReference/objc/AppDelegate.m @@ -14,6 +14,7 @@ // limitations under the License. // +@import FirebaseCore; @import FirebaseDatabase; #import "AppDelegate.h" diff --git a/database/DatabaseReference/objc/ViewController.m b/database/DatabaseReference/objc/ViewController.m index aaad3674..fa1844f1 100644 --- a/database/DatabaseReference/objc/ViewController.m +++ b/database/DatabaseReference/objc/ViewController.m @@ -13,6 +13,8 @@ // See the License for the specific language governing permissions and // limitations under the License. // + +@import FirebaseAuth; @import FirebaseDatabase; #import "ViewController.h" @@ -25,16 +27,6 @@ @interface ViewController () @implementation ViewController -- (void)viewDidLoad { - [super viewDidLoad]; - // Do any additional setup after loading the view. -} - -- (void)didReceiveMemoryWarning { - [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. -} - - (void)persistenceReference { // [START keep_synchronized] FIRDatabaseReference *scoresRef = [[FIRDatabase database] referenceWithPath:@"scores"]; diff --git a/database/DatabaseReference/swift/AppDelegate.swift b/database/DatabaseReference/swift/AppDelegate.swift index 9d15205b..60171b17 100644 --- a/database/DatabaseReference/swift/AppDelegate.swift +++ b/database/DatabaseReference/swift/AppDelegate.swift @@ -16,6 +16,7 @@ import UIKit +import FirebaseCore import FirebaseDatabase @UIApplicationMain diff --git a/database/DatabaseReference/swift/ViewController.swift b/database/DatabaseReference/swift/ViewController.swift index e554e88d..84b6291f 100644 --- a/database/DatabaseReference/swift/ViewController.swift +++ b/database/DatabaseReference/swift/ViewController.swift @@ -16,22 +16,13 @@ import UIKit +import FirebaseAuth import FirebaseDatabase class ViewController: UIViewController { var ref: DatabaseReference! - override func viewDidLoad() { - super.viewDidLoad() - // Do any additional setup after loading the view, typically from a nib. - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - func persistenceReference() { // [START keep_synchronized] let scoresRef = Database.database().reference(withPath: "scores") @@ -103,49 +94,46 @@ class ViewController: UIViewController { // [END clock_skew] } - func writeNewUser(_ user: Firebase.User, withUsername username: String) { + func writeNewUser(_ user: FirebaseAuth.User, withUsername username: String) { // [START rtdb_write_new_user] ref.child("users").child(user.uid).setValue(["username": username]) // [END rtdb_write_new_user] } - func writeNewUserWithCompletion(_ user: Firebase.User, withUsername username: String) { + func writeNewUserWithCompletion(_ user: FirebaseAuth.User, withUsername username: String) async { // [START rtdb_write_new_user_completion] - ref.child("users").child(user.uid).setValue(["username": username]) { - (error:Error?, ref:DatabaseReference) in - if let error = error { - print("Data could not be saved: \(error).") - } else { - print("Data saved successfully!") - } + do { + try await ref.child("users").child(user.uid).setValue(["username": username]) + print("Data saved successfully!") + } catch { + print("Data could not be saved: \(error).") } // [END rtdb_write_new_user_completion] } - func singleUseFetchData(uid: String) { - let ref = Database.database().reference(); + func singleUseFetchData(uid: String) async { + let ref = Database.database().reference() // [START single_value_get_data] - ref.child("users/\(uid)/username").getData(completion: { error, snapshot in - guard error == nil else { - print(error!.localizedDescription) - return; - } - let userName = snapshot.value as? String ?? "Unknown"; - }); + do { + let snapshot = try await ref.child("users/\(uid)/username").getData() + let userName = snapshot.value as? String ?? "Unknown" + } catch { + print(error) + } // [END single_value_get_data] } func emulatorSettings() { // [START rtdb_emulator_connect] // In almost all cases the ns (namespace) is your project ID. - let db = Database.database(url:"http://localhost:9000?ns=YOUR_DATABASE_NAMESPACE") + let db = Database.database(url:"http://127.0.0.1:9000?ns=YOUR_DATABASE_NAMESPACE") // [END rtdb_emulator_connect] } func flushRealtimeDatabase() { - // [START rtdb_emulator_flush] + // [START rtdb_emulator_flush] // With a DatabaseReference, write nil to clear the database. - Database.database().reference().setValue(nil); + Database.database().reference().setValue(nil) // [END rtdb_emulator_flush] } @@ -157,7 +145,7 @@ class ViewController: UIViewController { "user-posts/\(postID)/stars/\(userID)": true, "user-posts/\(postID)/starCount": ServerValue.increment(1) ] as [String : Any] - Database.database().reference().updateChildValues(updates); + Database.database().reference().updateChildValues(updates) // [END rtdb_post_stars_increment] } @@ -176,7 +164,7 @@ func combinedExample() { connectedRef.observe(.value, with: { snapshot in // only handle connection established (or I've reconnected after a loss of connection) - guard let connected = snapshot.value as? Bool, connected else { return } + guard snapshot.value as? Bool ?? false else { return } // add this device to my connections list let con = myConnectionsRef.childByAutoId() diff --git a/database/Podfile b/database/Podfile deleted file mode 100644 index b3eb4a09..00000000 --- a/database/Podfile +++ /dev/null @@ -1,8 +0,0 @@ -# Firebase Database ReferenceCode -use_frameworks! -platform :ios, '10.0' -pod 'Firebase/Database' -pod 'Firebase/Auth' - -target 'DatabaseReference' do -end diff --git a/database/Podfile.lock b/database/Podfile.lock deleted file mode 100644 index bd7607d0..00000000 --- a/database/Podfile.lock +++ /dev/null @@ -1,93 +0,0 @@ -PODS: - - Firebase/Auth (9.6.0): - - Firebase/CoreOnly - - FirebaseAuth (~> 9.6.0) - - Firebase/CoreOnly (9.6.0): - - FirebaseCore (= 9.6.0) - - Firebase/Database (9.6.0): - - Firebase/CoreOnly - - FirebaseDatabase (~> 9.6.0) - - FirebaseAuth (9.6.0): - - FirebaseCore (~> 9.0) - - GoogleUtilities/AppDelegateSwizzler (~> 7.7) - - GoogleUtilities/Environment (~> 7.7) - - GTMSessionFetcher/Core (< 3.0, >= 1.7) - - FirebaseCore (9.6.0): - - FirebaseCoreDiagnostics (~> 9.0) - - FirebaseCoreInternal (~> 9.0) - - GoogleUtilities/Environment (~> 7.7) - - GoogleUtilities/Logger (~> 7.7) - - FirebaseCoreDiagnostics (9.6.0): - - GoogleDataTransport (< 10.0.0, >= 9.1.4) - - GoogleUtilities/Environment (~> 7.7) - - GoogleUtilities/Logger (~> 7.7) - - nanopb (< 2.30910.0, >= 2.30908.0) - - FirebaseCoreInternal (9.6.0): - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - FirebaseDatabase (9.6.0): - - FirebaseCore (~> 9.0) - - leveldb-library (~> 1.22) - - GoogleDataTransport (9.2.0): - - GoogleUtilities/Environment (~> 7.7) - - nanopb (< 2.30910.0, >= 2.30908.0) - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/AppDelegateSwizzler (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/Logger - - GoogleUtilities/Network - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/Network (7.10.0): - - GoogleUtilities/Logger - - "GoogleUtilities/NSData+zlib" - - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GoogleUtilities/Reachability (7.10.0): - - GoogleUtilities/Logger - - GTMSessionFetcher/Core (2.3.0) - - leveldb-library (1.22.1) - - nanopb (2.30909.0): - - nanopb/decode (= 2.30909.0) - - nanopb/encode (= 2.30909.0) - - nanopb/decode (2.30909.0) - - nanopb/encode (2.30909.0) - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - Firebase/Auth - - Firebase/Database - -SPEC REPOS: - trunk: - - Firebase - - FirebaseAuth - - FirebaseCore - - FirebaseCoreDiagnostics - - FirebaseCoreInternal - - FirebaseDatabase - - GoogleDataTransport - - GoogleUtilities - - GTMSessionFetcher - - leveldb-library - - nanopb - - PromisesObjC - -SPEC CHECKSUMS: - Firebase: 5ae8b7cf8efce559a653aef0ad95bab3f427c351 - FirebaseAuth: e4a5d3c36e778e41141b91cc861103a441d80bcc - FirebaseCore: 2082fffcd855f95f883c0a1641133eb9bbe76d40 - FirebaseCoreDiagnostics: 99a495094b10a57eeb3ae8efa1665700ad0bdaa6 - FirebaseCoreInternal: bca76517fe1ed381e989f5e7d8abb0da8d85bed3 - FirebaseDatabase: 3de19e533a73d45e25917b46aafe1dd344ec8119 - GoogleDataTransport: 1c8145da7117bd68bbbed00cf304edb6a24de00f - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - GTMSessionFetcher: 3a63d75eecd6aa32c2fc79f578064e1214dfdec2 - leveldb-library: 50c7b45cbd7bf543c81a468fe557a16ae3db8729 - nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 2613ab7c1eac1e9efb615f9c2979ec498d92dcf6 - -COCOAPODS: 1.11.3 diff --git a/dl-invites-sample/Podfile.lock b/dl-invites-sample/Podfile.lock index 8c009938..a38be10b 100644 --- a/dl-invites-sample/Podfile.lock +++ b/dl-invites-sample/Podfile.lock @@ -54,4 +54,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 7de02ed38e9465e2c05bb12085a971c35543c261 -COCOAPODS: 1.11.3 +COCOAPODS: 1.15.2 diff --git a/firestore/objc/Podfile b/firestore/objc/Podfile deleted file mode 100644 index f2e737a5..00000000 --- a/firestore/objc/Podfile +++ /dev/null @@ -1,17 +0,0 @@ -# Uncomment the next line to define a global platform for your project -platform :ios, '12.0' - -target 'firestore-smoketest-objc' do - - use_frameworks! - - # Pods for firestore-smoketest - pod 'FirebaseAuth' - pod 'FirebaseFirestore' - - target 'firestore-smoketest-objcTests' do - inherit! :search_paths - # Pods for testing - end - -end diff --git a/firestore/objc/Podfile.lock b/firestore/objc/Podfile.lock deleted file mode 100644 index f6eb86c1..00000000 --- a/firestore/objc/Podfile.lock +++ /dev/null @@ -1,749 +0,0 @@ -PODS: - - abseil/algorithm (1.20211102.0): - - abseil/algorithm/algorithm (= 1.20211102.0) - - abseil/algorithm/container (= 1.20211102.0) - - abseil/algorithm/algorithm (1.20211102.0): - - abseil/base/config - - abseil/algorithm/container (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/base (1.20211102.0): - - abseil/base/atomic_hook (= 1.20211102.0) - - abseil/base/base (= 1.20211102.0) - - abseil/base/base_internal (= 1.20211102.0) - - abseil/base/config (= 1.20211102.0) - - abseil/base/core_headers (= 1.20211102.0) - - abseil/base/dynamic_annotations (= 1.20211102.0) - - abseil/base/endian (= 1.20211102.0) - - abseil/base/errno_saver (= 1.20211102.0) - - abseil/base/fast_type_id (= 1.20211102.0) - - abseil/base/log_severity (= 1.20211102.0) - - abseil/base/malloc_internal (= 1.20211102.0) - - abseil/base/pretty_function (= 1.20211102.0) - - abseil/base/raw_logging_internal (= 1.20211102.0) - - abseil/base/spinlock_wait (= 1.20211102.0) - - abseil/base/strerror (= 1.20211102.0) - - abseil/base/throw_delegate (= 1.20211102.0) - - abseil/base/atomic_hook (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/base (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/log_severity - - abseil/base/raw_logging_internal - - abseil/base/spinlock_wait - - abseil/meta/type_traits - - abseil/base/base_internal (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/base/config (1.20211102.0) - - abseil/base/core_headers (1.20211102.0): - - abseil/base/config - - abseil/base/dynamic_annotations (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/errno_saver (1.20211102.0): - - abseil/base/config - - abseil/base/fast_type_id (1.20211102.0): - - abseil/base/config - - abseil/base/log_severity (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/malloc_internal (1.20211102.0): - - abseil/base/base - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/raw_logging_internal - - abseil/base/pretty_function (1.20211102.0) - - abseil/base/raw_logging_internal (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/config - - abseil/base/core_headers - - abseil/base/log_severity - - abseil/base/spinlock_wait (1.20211102.0): - - abseil/base/base_internal - - abseil/base/core_headers - - abseil/base/errno_saver - - abseil/base/strerror (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/errno_saver - - abseil/base/throw_delegate (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/container/common (1.20211102.0): - - abseil/meta/type_traits - - abseil/types/optional - - abseil/container/compressed_tuple (1.20211102.0): - - abseil/utility/utility - - abseil/container/container_memory (1.20211102.0): - - abseil/base/config - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/utility/utility - - abseil/container/fixed_array (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/throw_delegate - - abseil/container/compressed_tuple - - abseil/memory/memory - - abseil/container/flat_hash_map (1.20211102.0): - - abseil/algorithm/container - - abseil/container/container_memory - - abseil/container/hash_function_defaults - - abseil/container/raw_hash_map - - abseil/memory/memory - - abseil/container/hash_function_defaults (1.20211102.0): - - abseil/base/config - - abseil/hash/hash - - abseil/strings/cord - - abseil/strings/strings - - abseil/container/hash_policy_traits (1.20211102.0): - - abseil/meta/type_traits - - abseil/container/hashtable_debug_hooks (1.20211102.0): - - abseil/base/config - - abseil/container/hashtablez_sampler (1.20211102.0): - - abseil/base/base - - abseil/base/core_headers - - abseil/container/have_sse - - abseil/debugging/stacktrace - - abseil/memory/memory - - abseil/profiling/exponential_biased - - abseil/profiling/sample_recorder - - abseil/synchronization/synchronization - - abseil/utility/utility - - abseil/container/have_sse (1.20211102.0) - - abseil/container/inlined_vector (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/core_headers - - abseil/base/throw_delegate - - abseil/container/inlined_vector_internal - - abseil/memory/memory - - abseil/container/inlined_vector_internal (1.20211102.0): - - abseil/base/core_headers - - abseil/container/compressed_tuple - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/types/span - - abseil/container/layout (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/strings/strings - - abseil/types/span - - abseil/utility/utility - - abseil/container/raw_hash_map (1.20211102.0): - - abseil/base/throw_delegate - - abseil/container/container_memory - - abseil/container/raw_hash_set - - abseil/container/raw_hash_set (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/container/common - - abseil/container/compressed_tuple - - abseil/container/container_memory - - abseil/container/hash_policy_traits - - abseil/container/hashtable_debug_hooks - - abseil/container/hashtablez_sampler - - abseil/container/have_sse - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/utility/utility - - abseil/debugging/debugging_internal (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/errno_saver - - abseil/base/raw_logging_internal - - abseil/debugging/demangle_internal (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/debugging/stacktrace (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/debugging/debugging_internal - - abseil/debugging/symbolize (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/malloc_internal - - abseil/base/raw_logging_internal - - abseil/debugging/debugging_internal - - abseil/debugging/demangle_internal - - abseil/strings/strings - - abseil/functional/bind_front (1.20211102.0): - - abseil/base/base_internal - - abseil/container/compressed_tuple - - abseil/meta/type_traits - - abseil/utility/utility - - abseil/functional/function_ref (1.20211102.0): - - abseil/base/base_internal - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/hash/city (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/hash/hash (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/container/fixed_array - - abseil/hash/city - - abseil/hash/low_level_hash - - abseil/meta/type_traits - - abseil/numeric/int128 - - abseil/strings/strings - - abseil/types/optional - - abseil/types/variant - - abseil/utility/utility - - abseil/hash/low_level_hash (1.20211102.0): - - abseil/base/config - - abseil/base/endian - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/memory (1.20211102.0): - - abseil/memory/memory (= 1.20211102.0) - - abseil/memory/memory (1.20211102.0): - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/meta (1.20211102.0): - - abseil/meta/type_traits (= 1.20211102.0) - - abseil/meta/type_traits (1.20211102.0): - - abseil/base/config - - abseil/numeric/bits (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/numeric/int128 (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/numeric/bits - - abseil/numeric/representation (1.20211102.0): - - abseil/base/config - - abseil/profiling/exponential_biased (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/profiling/sample_recorder (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/synchronization/synchronization - - abseil/time/time - - abseil/random/distributions (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/random/internal/distribution_caller - - abseil/random/internal/fast_uniform_bits - - abseil/random/internal/fastmath - - abseil/random/internal/generate_real - - abseil/random/internal/iostream_state_saver - - abseil/random/internal/traits - - abseil/random/internal/uniform_helper - - abseil/random/internal/wide_multiply - - abseil/strings/strings - - abseil/random/internal/distribution_caller (1.20211102.0): - - abseil/base/config - - abseil/base/fast_type_id - - abseil/utility/utility - - abseil/random/internal/fast_uniform_bits (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/random/internal/fastmath (1.20211102.0): - - abseil/numeric/bits - - abseil/random/internal/generate_real (1.20211102.0): - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/random/internal/fastmath - - abseil/random/internal/traits - - abseil/random/internal/iostream_state_saver (1.20211102.0): - - abseil/meta/type_traits - - abseil/numeric/int128 - - abseil/random/internal/nonsecure_base (1.20211102.0): - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/random/internal/pool_urbg - - abseil/random/internal/salted_seed_seq - - abseil/random/internal/seed_material - - abseil/types/optional - - abseil/types/span - - abseil/random/internal/pcg_engine (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/random/internal/fastmath - - abseil/random/internal/iostream_state_saver - - abseil/random/internal/platform (1.20211102.0): - - abseil/base/config - - abseil/random/internal/pool_urbg (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/random/internal/randen - - abseil/random/internal/seed_material - - abseil/random/internal/traits - - abseil/random/seed_gen_exception - - abseil/types/span - - abseil/random/internal/randen (1.20211102.0): - - abseil/base/raw_logging_internal - - abseil/random/internal/platform - - abseil/random/internal/randen_hwaes - - abseil/random/internal/randen_slow - - abseil/random/internal/randen_engine (1.20211102.0): - - abseil/base/endian - - abseil/meta/type_traits - - abseil/random/internal/iostream_state_saver - - abseil/random/internal/randen - - abseil/random/internal/randen_hwaes (1.20211102.0): - - abseil/base/config - - abseil/random/internal/platform - - abseil/random/internal/randen_hwaes_impl - - abseil/random/internal/randen_hwaes_impl (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/numeric/int128 - - abseil/random/internal/platform - - abseil/random/internal/randen_slow (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/numeric/int128 - - abseil/random/internal/platform - - abseil/random/internal/salted_seed_seq (1.20211102.0): - - abseil/container/inlined_vector - - abseil/meta/type_traits - - abseil/random/internal/seed_material - - abseil/types/optional - - abseil/types/span - - abseil/random/internal/seed_material (1.20211102.0): - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/raw_logging_internal - - abseil/random/internal/fast_uniform_bits - - abseil/strings/strings - - abseil/types/optional - - abseil/types/span - - abseil/random/internal/traits (1.20211102.0): - - abseil/base/config - - abseil/random/internal/uniform_helper (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/random/internal/traits - - abseil/random/internal/wide_multiply (1.20211102.0): - - abseil/base/config - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/random/internal/traits - - abseil/random/random (1.20211102.0): - - abseil/random/distributions - - abseil/random/internal/nonsecure_base - - abseil/random/internal/pcg_engine - - abseil/random/internal/pool_urbg - - abseil/random/internal/randen_engine - - abseil/random/seed_sequences - - abseil/random/seed_gen_exception (1.20211102.0): - - abseil/base/config - - abseil/random/seed_sequences (1.20211102.0): - - abseil/container/inlined_vector - - abseil/random/internal/nonsecure_base - - abseil/random/internal/pool_urbg - - abseil/random/internal/salted_seed_seq - - abseil/random/internal/seed_material - - abseil/random/seed_gen_exception - - abseil/types/span - - abseil/status/status (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/config - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/container/inlined_vector - - abseil/debugging/stacktrace - - abseil/debugging/symbolize - - abseil/functional/function_ref - - abseil/strings/cord - - abseil/strings/str_format - - abseil/strings/strings - - abseil/types/optional - - abseil/status/statusor (1.20211102.0): - - abseil/base/base - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/meta/type_traits - - abseil/status/status - - abseil/strings/strings - - abseil/types/variant - - abseil/utility/utility - - abseil/strings/cord (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/container/fixed_array - - abseil/container/inlined_vector - - abseil/functional/function_ref - - abseil/meta/type_traits - - abseil/strings/cord_internal - - abseil/strings/cordz_functions - - abseil/strings/cordz_info - - abseil/strings/cordz_statistics - - abseil/strings/cordz_update_scope - - abseil/strings/cordz_update_tracker - - abseil/strings/internal - - abseil/strings/str_format - - abseil/strings/strings - - abseil/types/optional - - abseil/strings/cord_internal (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/base/throw_delegate - - abseil/container/compressed_tuple - - abseil/container/inlined_vector - - abseil/container/layout - - abseil/functional/function_ref - - abseil/meta/type_traits - - abseil/strings/strings - - abseil/types/span - - abseil/strings/cordz_functions (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/profiling/exponential_biased - - abseil/strings/cordz_handle (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/synchronization/synchronization - - abseil/strings/cordz_info (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/container/inlined_vector - - abseil/debugging/stacktrace - - abseil/strings/cord_internal - - abseil/strings/cordz_functions - - abseil/strings/cordz_handle - - abseil/strings/cordz_statistics - - abseil/strings/cordz_update_tracker - - abseil/synchronization/synchronization - - abseil/types/span - - abseil/strings/cordz_statistics (1.20211102.0): - - abseil/base/config - - abseil/strings/cordz_update_tracker - - abseil/strings/cordz_update_scope (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/strings/cord_internal - - abseil/strings/cordz_info - - abseil/strings/cordz_update_tracker - - abseil/strings/cordz_update_tracker (1.20211102.0): - - abseil/base/config - - abseil/strings/internal (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/meta/type_traits - - abseil/strings/str_format (1.20211102.0): - - abseil/strings/str_format_internal - - abseil/strings/str_format_internal (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/functional/function_ref - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/numeric/representation - - abseil/strings/strings - - abseil/types/optional - - abseil/types/span - - abseil/strings/strings (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/base/throw_delegate - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/strings/internal - - abseil/synchronization/graphcycles_internal (1.20211102.0): - - abseil/base/base - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/malloc_internal - - abseil/base/raw_logging_internal - - abseil/synchronization/kernel_timeout_internal (1.20211102.0): - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/time/time - - abseil/synchronization/synchronization (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/base - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/malloc_internal - - abseil/base/raw_logging_internal - - abseil/debugging/stacktrace - - abseil/debugging/symbolize - - abseil/synchronization/graphcycles_internal - - abseil/synchronization/kernel_timeout_internal - - abseil/time/time - - abseil/time (1.20211102.0): - - abseil/time/internal (= 1.20211102.0) - - abseil/time/time (= 1.20211102.0) - - abseil/time/internal (1.20211102.0): - - abseil/time/internal/cctz (= 1.20211102.0) - - abseil/time/internal/cctz (1.20211102.0): - - abseil/time/internal/cctz/civil_time (= 1.20211102.0) - - abseil/time/internal/cctz/time_zone (= 1.20211102.0) - - abseil/time/internal/cctz/civil_time (1.20211102.0): - - abseil/base/config - - abseil/time/internal/cctz/time_zone (1.20211102.0): - - abseil/base/config - - abseil/time/internal/cctz/civil_time - - abseil/time/time (1.20211102.0): - - abseil/base/base - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/numeric/int128 - - abseil/strings/strings - - abseil/time/internal/cctz/civil_time - - abseil/time/internal/cctz/time_zone - - abseil/types (1.20211102.0): - - abseil/types/any (= 1.20211102.0) - - abseil/types/bad_any_cast (= 1.20211102.0) - - abseil/types/bad_any_cast_impl (= 1.20211102.0) - - abseil/types/bad_optional_access (= 1.20211102.0) - - abseil/types/bad_variant_access (= 1.20211102.0) - - abseil/types/compare (= 1.20211102.0) - - abseil/types/optional (= 1.20211102.0) - - abseil/types/span (= 1.20211102.0) - - abseil/types/variant (= 1.20211102.0) - - abseil/types/any (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/fast_type_id - - abseil/meta/type_traits - - abseil/types/bad_any_cast - - abseil/utility/utility - - abseil/types/bad_any_cast (1.20211102.0): - - abseil/base/config - - abseil/types/bad_any_cast_impl - - abseil/types/bad_any_cast_impl (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/types/bad_optional_access (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/types/bad_variant_access (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/types/compare (1.20211102.0): - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/types/optional (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/types/bad_optional_access - - abseil/utility/utility - - abseil/types/span (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/core_headers - - abseil/base/throw_delegate - - abseil/meta/type_traits - - abseil/types/variant (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/types/bad_variant_access - - abseil/utility/utility - - abseil/utility/utility (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/meta/type_traits - - BoringSSL-GRPC (0.0.24): - - BoringSSL-GRPC/Implementation (= 0.0.24) - - BoringSSL-GRPC/Interface (= 0.0.24) - - BoringSSL-GRPC/Implementation (0.0.24): - - BoringSSL-GRPC/Interface (= 0.0.24) - - BoringSSL-GRPC/Interface (0.0.24) - - FirebaseAuth (10.2.0): - - FirebaseCore (~> 10.0) - - GoogleUtilities/AppDelegateSwizzler (~> 7.8) - - GoogleUtilities/Environment (~> 7.8) - - GTMSessionFetcher/Core (< 4.0, >= 2.1) - - FirebaseCore (10.2.0): - - FirebaseCoreInternal (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/Logger (~> 7.8) - - FirebaseCoreInternal (10.2.0): - - "GoogleUtilities/NSData+zlib (~> 7.8)" - - FirebaseFirestore (10.2.0): - - abseil/algorithm (~> 1.20211102.0) - - abseil/base (~> 1.20211102.0) - - abseil/container/flat_hash_map (~> 1.20211102.0) - - abseil/memory (~> 1.20211102.0) - - abseil/meta (~> 1.20211102.0) - - abseil/strings/strings (~> 1.20211102.0) - - abseil/time (~> 1.20211102.0) - - abseil/types (~> 1.20211102.0) - - FirebaseCore (~> 10.0) - - "gRPC-C++ (~> 1.44.0)" - - leveldb-library (~> 1.22) - - nanopb (< 2.30910.0, >= 2.30908.0) - - GoogleUtilities/AppDelegateSwizzler (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/Logger - - GoogleUtilities/Network - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/Network (7.10.0): - - GoogleUtilities/Logger - - "GoogleUtilities/NSData+zlib" - - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GoogleUtilities/Reachability (7.10.0): - - GoogleUtilities/Logger - - "gRPC-C++ (1.44.0)": - - "gRPC-C++/Implementation (= 1.44.0)" - - "gRPC-C++/Interface (= 1.44.0)" - - "gRPC-C++/Implementation (1.44.0)": - - abseil/base/base (= 1.20211102.0) - - abseil/base/core_headers (= 1.20211102.0) - - abseil/container/flat_hash_map (= 1.20211102.0) - - abseil/container/inlined_vector (= 1.20211102.0) - - abseil/functional/bind_front (= 1.20211102.0) - - abseil/hash/hash (= 1.20211102.0) - - abseil/memory/memory (= 1.20211102.0) - - abseil/random/random (= 1.20211102.0) - - abseil/status/status (= 1.20211102.0) - - abseil/status/statusor (= 1.20211102.0) - - abseil/strings/cord (= 1.20211102.0) - - abseil/strings/str_format (= 1.20211102.0) - - abseil/strings/strings (= 1.20211102.0) - - abseil/synchronization/synchronization (= 1.20211102.0) - - abseil/time/time (= 1.20211102.0) - - abseil/types/optional (= 1.20211102.0) - - abseil/types/variant (= 1.20211102.0) - - abseil/utility/utility (= 1.20211102.0) - - "gRPC-C++/Interface (= 1.44.0)" - - gRPC-Core (= 1.44.0) - - "gRPC-C++/Interface (1.44.0)" - - gRPC-Core (1.44.0): - - gRPC-Core/Implementation (= 1.44.0) - - gRPC-Core/Interface (= 1.44.0) - - gRPC-Core/Implementation (1.44.0): - - abseil/base/base (= 1.20211102.0) - - abseil/base/core_headers (= 1.20211102.0) - - abseil/container/flat_hash_map (= 1.20211102.0) - - abseil/container/inlined_vector (= 1.20211102.0) - - abseil/functional/bind_front (= 1.20211102.0) - - abseil/hash/hash (= 1.20211102.0) - - abseil/memory/memory (= 1.20211102.0) - - abseil/random/random (= 1.20211102.0) - - abseil/status/status (= 1.20211102.0) - - abseil/status/statusor (= 1.20211102.0) - - abseil/strings/cord (= 1.20211102.0) - - abseil/strings/str_format (= 1.20211102.0) - - abseil/strings/strings (= 1.20211102.0) - - abseil/synchronization/synchronization (= 1.20211102.0) - - abseil/time/time (= 1.20211102.0) - - abseil/types/optional (= 1.20211102.0) - - abseil/types/variant (= 1.20211102.0) - - abseil/utility/utility (= 1.20211102.0) - - BoringSSL-GRPC (= 0.0.24) - - gRPC-Core/Interface (= 1.44.0) - - Libuv-gRPC (= 0.0.10) - - gRPC-Core/Interface (1.44.0) - - GTMSessionFetcher/Core (3.0.0) - - leveldb-library (1.22.1) - - Libuv-gRPC (0.0.10): - - Libuv-gRPC/Implementation (= 0.0.10) - - Libuv-gRPC/Interface (= 0.0.10) - - Libuv-gRPC/Implementation (0.0.10): - - Libuv-gRPC/Interface (= 0.0.10) - - Libuv-gRPC/Interface (0.0.10) - - nanopb (2.30909.0): - - nanopb/decode (= 2.30909.0) - - nanopb/encode (= 2.30909.0) - - nanopb/decode (2.30909.0) - - nanopb/encode (2.30909.0) - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - FirebaseAuth - - FirebaseFirestore - -SPEC REPOS: - trunk: - - abseil - - BoringSSL-GRPC - - FirebaseAuth - - FirebaseCore - - FirebaseCoreInternal - - FirebaseFirestore - - GoogleUtilities - - "gRPC-C++" - - gRPC-Core - - GTMSessionFetcher - - leveldb-library - - Libuv-gRPC - - nanopb - - PromisesObjC - -SPEC CHECKSUMS: - abseil: ebe5b5529fb05d93a8bdb7951607be08b7fa71bc - BoringSSL-GRPC: 3175b25143e648463a56daeaaa499c6cb86dad33 - FirebaseAuth: 08e7739244eeae5216d0a3f8d9f16a76be9c252e - FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1 - FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f - FirebaseFirestore: bda7a1ca8c19319a2acd2761cd4b962022c1d5ea - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - "gRPC-C++": 9675f953ace2b3de7c506039d77be1f2e77a8db2 - gRPC-Core: 943e491cb0d45598b0b0eb9e910c88080369290b - GTMSessionFetcher: c1edebe64e9fb4e8f6415d018edf1fd3eac074a1 - leveldb-library: 50c7b45cbd7bf543c81a468fe557a16ae3db8729 - Libuv-gRPC: 55e51798e14ef436ad9bc45d12d43b77b49df378 - nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 2c326f47761ecd18d1c150444d24a282c84b433e - -COCOAPODS: 1.11.3 diff --git a/firestore/objc/firestore-smoketest-objc.xcodeproj/project.pbxproj b/firestore/objc/firestore-smoketest-objc.xcodeproj/project.pbxproj index d95a7a0e..2c8e8536 100644 --- a/firestore/objc/firestore-smoketest-objc.xcodeproj/project.pbxproj +++ b/firestore/objc/firestore-smoketest-objc.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -18,6 +18,8 @@ 8D70FC2A1F4CAE1B00C7F603 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8D70FC291F4CAE1B00C7F603 /* Assets.xcassets */; }; 8D70FC2D1F4CAE1B00C7F603 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D70FC2B1F4CAE1B00C7F603 /* LaunchScreen.storyboard */; }; 8D70FC381F4CAE1B00C7F603 /* firestore_smoketest_objcTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D70FC371F4CAE1B00C7F603 /* firestore_smoketest_objcTests.m */; }; + 8D79519D2D28ABAD000FD694 /* FirebaseAuth in Frameworks */ = {isa = PBXBuildFile; productRef = 8D79519C2D28ABAD000FD694 /* FirebaseAuth */; }; + 8D79519F2D28ABAD000FD694 /* FirebaseFirestore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D79519E2D28ABAD000FD694 /* FirebaseFirestore */; }; 8D9644E7260D565A002A46C9 /* FIRSolutionsBundleViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D9644E6260D565A002A46C9 /* FIRSolutionsBundleViewController.m */; }; /* End PBXBuildFile section */ @@ -61,6 +63,8 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D79519D2D28ABAD000FD694 /* FirebaseAuth in Frameworks */, + 8D79519F2D28ABAD000FD694 /* FirebaseFirestore in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -80,8 +84,8 @@ 8D4F2EF1201162EE002ED308 /* GoogleService-Info.plist */, 8D70FC1C1F4CAE1B00C7F603 /* firestore-smoketest-objc */, 8D70FC361F4CAE1B00C7F603 /* firestore-smoketest-objcTests */, + 8D79519B2D28ABAD000FD694 /* Frameworks */, 8D70FC1B1F4CAE1B00C7F603 /* Products */, - F792628F569A18209F7C4E90 /* Pods */, ); sourceTree = ""; }; @@ -135,11 +139,11 @@ path = "firestore-smoketest-objcTests"; sourceTree = ""; }; - F792628F569A18209F7C4E90 /* Pods */ = { + 8D79519B2D28ABAD000FD694 /* Frameworks */ = { isa = PBXGroup; children = ( ); - path = Pods; + name = Frameworks; sourceTree = ""; }; /* End PBXGroup section */ @@ -209,6 +213,9 @@ Base, ); mainGroup = 8D70FC111F4CAE1B00C7F603; + packageReferences = ( + 8D79519A2D28AB9C000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 8D70FC1B1F4CAE1B00C7F603 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -408,7 +415,10 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = "firestore-smoketest-objc/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.firebase.firestore-smoketest-objc"; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -419,7 +429,10 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = "firestore-smoketest-objc/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.firebase.firestore-smoketest-objc"; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -430,7 +443,11 @@ buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = "firestore-smoketest-objcTests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.firebase.firestore-smoketest-objcTests"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/firestore-smoketest-objc.app/firestore-smoketest-objc"; @@ -442,7 +459,11 @@ buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = "firestore-smoketest-objcTests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.firebase.firestore-smoketest-objcTests"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/firestore-smoketest-objc.app/firestore-smoketest-objc"; @@ -480,6 +501,30 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D79519A2D28AB9C000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D79519C2D28ABAD000FD694 /* FirebaseAuth */ = { + isa = XCSwiftPackageProductDependency; + package = 8D79519A2D28AB9C000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAuth; + }; + 8D79519E2D28ABAD000FD694 /* FirebaseFirestore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D79519A2D28AB9C000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseFirestore; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 8D70FC121F4CAE1B00C7F603 /* Project object */; } diff --git a/firestore/objc/firestore-smoketest-objc/ViewController.m b/firestore/objc/firestore-smoketest-objc/ViewController.m index 46da5bf1..9e448c36 100644 --- a/firestore/objc/firestore-smoketest-objc/ViewController.m +++ b/firestore/objc/firestore-smoketest-objc/ViewController.m @@ -78,28 +78,30 @@ - (void)viewDidLoad { // ======================================================================================= - (void)setupCacheSize { - // [START fs_setup_cache] - FIRFirestoreSettings *settings = [FIRFirestore firestore].settings; - settings.cacheSizeBytes = kFIRFirestoreCacheSizeUnlimited; - [FIRFirestore firestore].settings = settings; - // [END fs_setup_cache] + // [START fs_setup_cache] + FIRFirestoreSettings *settings = [FIRFirestore firestore].settings; + // Set cache size to 100 MB + settings.cacheSettings = + [[FIRPersistentCacheSettings alloc] initWithSizeBytes:@(100 * 1024 * 1024)]; + [FIRFirestore firestore].settings = settings; + // [END fs_setup_cache] } - (void)addAdaLovelace { // [START add_ada_lovelace] // Add a new document with a generated ID __block FIRDocumentReference *ref = - [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ - @"first": @"Ada", - @"last": @"Lovelace", - @"born": @1815 - } completion:^(NSError * _Nullable error) { - if (error != nil) { - NSLog(@"Error adding document: %@", error); - } else { - NSLog(@"Document added with ID: %@", ref.documentID); - } - }]; + [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ + @"first": @"Ada", + @"last": @"Lovelace", + @"born": @1815 + } completion:^(NSError * _Nullable error) { + if (error != nil) { + NSLog(@"Error adding document: %@", error); + } else { + NSLog(@"Document added with ID: %@", ref.documentID); + } + }]; // [END add_ada_lovelace] } @@ -107,34 +109,34 @@ - (void)addAlanTuring { // [START add_alan_turing] // Add a second document with a generated ID. __block FIRDocumentReference *ref = - [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ - @"first": @"Alan", - @"middle": @"Mathison", - @"last": @"Turing", - @"born": @1912 - } completion:^(NSError * _Nullable error) { - if (error != nil) { - NSLog(@"Error adding document: %@", error); - } else { - NSLog(@"Document added with ID: %@", ref.documentID); - } - }]; + [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ + @"first": @"Alan", + @"middle": @"Mathison", + @"last": @"Turing", + @"born": @1912 + } completion:^(NSError * _Nullable error) { + if (error != nil) { + NSLog(@"Error adding document: %@", error); + } else { + NSLog(@"Document added with ID: %@", ref.documentID); + } + }]; // [END add_alan_turing] } - (void)getCollection { // [START get_collection] [[self.db collectionWithPath:@"users"] - getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, - NSError * _Nullable error) { - if (error != nil) { - NSLog(@"Error getting documents: %@", error); - } else { - for (FIRDocumentSnapshot *document in snapshot.documents) { - NSLog(@"%@ => %@", document.documentID, document.data); - } - } - }]; + getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, + NSError * _Nullable error) { + if (error != nil) { + NSLog(@"Error getting documents: %@", error); + } else { + for (FIRDocumentSnapshot *document in snapshot.documents) { + NSLog(@"%@ => %@", document.documentID, document.data); + } + } + }]; // [END get_collection] } @@ -145,17 +147,17 @@ - (void)listenForUsers { // We will get a first snapshot with the initial results and a new // snapshot each time there is a change in the results. [[[self.db collectionWithPath:@"users"] queryWhereField:@"born" isLessThan:@1900] - addSnapshotListener:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { - if (error != nil) { - NSLog(@"Error retreiving snapshots %@", error); - } else { - NSMutableArray *users = [NSMutableArray array]; - for (FIRDocumentSnapshot *user in snapshot.documents) { - [users addObject:user.data]; - } - NSLog(@"Current users born before 1900: %@", users); - } - }]; + addSnapshotListener:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { + if (error != nil) { + NSLog(@"Error retreiving snapshots %@", error); + } else { + NSMutableArray *users = [NSMutableArray array]; + for (FIRDocumentSnapshot *user in snapshot.documents) { + [users addObject:user.data]; + } + NSLog(@"Current users born before 1900: %@", users); + } + }]; // [END listen_for_users] } @@ -166,7 +168,7 @@ - (void)listenForUsers { - (void)demonstrateReferences { // [START doc_reference] FIRDocumentReference *alovelaceDocumentRef = - [[self.db collectionWithPath:@"users"] documentWithPath:@"alovelace"]; + [[self.db collectionWithPath:@"users"] documentWithPath:@"alovelace"]; // [END doc_reference] NSLog(@"%@", alovelaceDocumentRef); // [START collection_reference] @@ -175,14 +177,14 @@ - (void)demonstrateReferences { NSLog(@"%@", usersCollectionRef); // [START subcollection_reference] FIRDocumentReference *messageRef = - [[[[self.db collectionWithPath:@"rooms"] documentWithPath:@"roomA"] - collectionWithPath:@"messages"] documentWithPath:@"message1"]; + [[[[self.db collectionWithPath:@"rooms"] documentWithPath:@"roomA"] + collectionWithPath:@"messages"] documentWithPath:@"message1"]; // [END subcollection_reference] NSLog(@"%@", messageRef); // [START path_reference] FIRDocumentReference *aLovelaceDocumentReference = - [self.db documentWithPath:@"users/alovelace"]; + [self.db documentWithPath:@"users/alovelace"]; // [END path_reference] NSLog(@"%@", aLovelaceDocumentReference); } @@ -226,13 +228,13 @@ - (void)dataTypes { }; [[[self.db collectionWithPath:@"data"] documentWithPath:@"one"] setData:docData - completion:^(NSError * _Nullable error) { - if (error != nil) { - NSLog(@"Error writing document: %@", error); - } else { - NSLog(@"Document successfully written!"); - } - }]; + completion:^(NSError * _Nullable error) { + if (error != nil) { + NSLog(@"Error writing document: %@", error); + } else { + NSLog(@"Document successfully written!"); + } + }]; // [END data_types] } @@ -240,7 +242,7 @@ - (void)setData { NSDictionary *data = @{ @"name": @"Beijing" }; // [START set_data] [[[self.db collectionWithPath:@"cities"] documentWithPath:@"new-city-id"] - setData:data]; + setData:data]; // [END set_data] } @@ -248,16 +250,16 @@ - (void)addDocument { // [START add_document] // Add a new document with a generated id. __block FIRDocumentReference *ref = - [[self.db collectionWithPath:@"cities"] addDocumentWithData:@{ - @"name": @"Tokyo", - @"country": @"Japan" - } completion:^(NSError * _Nullable error) { - if (error != nil) { - NSLog(@"Error adding document: %@", error); - } else { - NSLog(@"Document added with ID: %@", ref.documentID); - } - }]; + [[self.db collectionWithPath:@"cities"] addDocumentWithData:@{ + @"name": @"Tokyo", + @"country": @"Japan" + } completion:^(NSError * _Nullable error) { + if (error != nil) { + NSLog(@"Error adding document: %@", error); + } else { + NSLog(@"Document added with ID: %@", ref.documentID); + } + }]; // [END add_document] } @@ -272,7 +274,7 @@ - (void)newDocument { - (void)updateDocument { // [START update_document] FIRDocumentReference *washingtonRef = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; // Set the "capital" field of the city [washingtonRef updateData:@{ @"capital": @YES @@ -289,7 +291,7 @@ - (void)updateDocument { - (void)updateDocumentArray { // [START update_document_array] FIRDocumentReference *washingtonRef = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; // Atomically add a new region to the "regions" array field. [washingtonRef updateData:@{ @@ -306,7 +308,7 @@ - (void)updateDocumentArray { - (void)updateDocumentIncrement { // [START update_document_increment] FIRDocumentReference *washingtonRef = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; // Atomically increment the population of the city by 50. // Note that increment() with no arguments increments by 1. @@ -321,11 +323,11 @@ - (void)createIfMissing { // Write to the document reference, merging data with existing // if the document already exists [[[self.db collectionWithPath:@"cities"] documentWithPath:@"BJ"] - setData:@{ @"capital": @YES } - merge:YES - completion:^(NSError * _Nullable error) { - // ... - }]; + setData:@{ @"capital": @YES } + merge:YES + completion:^(NSError * _Nullable error) { + // ... + }]; // [END create_if_missing] } @@ -333,7 +335,7 @@ - (void)updateDocumentNested { // [START update_document_nested] // Create an initial document to update. FIRDocumentReference *frankDocRef = - [[self.db collectionWithPath:@"users"] documentWithPath:@"frank"]; + [[self.db collectionWithPath:@"users"] documentWithPath:@"frank"]; [frankDocRef setData:@{ @"name": @"Frank", @"favorites": @{ @@ -360,12 +362,12 @@ - (void)updateDocumentNested { - (void)deleteDocument { // [START delete_document] [[[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"] - deleteDocumentWithCompletion:^(NSError * _Nullable error) { - if (error != nil) { - NSLog(@"Error removing document: %@", error); - } else { - NSLog(@"Document successfully removed!"); - } + deleteDocumentWithCompletion:^(NSError * _Nullable error) { + if (error != nil) { + NSLog(@"Error removing document: %@", error); + } else { + NSLog(@"Document successfully removed!"); + } }]; // [END delete_document] } @@ -377,33 +379,33 @@ - (void)deleteCollection:(FIRCollectionReference *)collection // Limit query to avoid out-of-memory errors when deleting large collections. // When deleting a collection guaranteed to fit in memory, batching can be avoided entirely. [[collection queryLimitedTo:batchSize] - getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (error != nil) { - // An error occurred. - if (completion != nil) { completion(error); } - return; - } - if (snapshot.count == 0) { - // There's nothing to delete. - if (completion != nil) { completion(nil); } - return; - } + getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (error != nil) { + // An error occurred. + if (completion != nil) { completion(error); } + return; + } + if (snapshot.count == 0) { + // There's nothing to delete. + if (completion != nil) { completion(nil); } + return; + } - FIRWriteBatch *batch = [collection.firestore batch]; - for (FIRDocumentSnapshot *document in snapshot.documents) { - [batch deleteDocument:document.reference]; - } + FIRWriteBatch *batch = [collection.firestore batch]; + for (FIRDocumentSnapshot *document in snapshot.documents) { + [batch deleteDocument:document.reference]; + } - [batch commitWithCompletion:^(NSError *batchError) { - if (batchError != nil) { - // Stop the deletion process and handle the error. Some elements - // may have been deleted. - completion(batchError); - } else { - [self deleteCollection:collection batchSize:batchSize completion:completion]; - } - }]; - }]; + [batch commitWithCompletion:^(NSError *batchError) { + if (batchError != nil) { + // Stop the deletion process and handle the error. Some elements + // may have been deleted. + completion(batchError); + } else { + [self deleteCollection:collection batchSize:batchSize completion:completion]; + } + }]; + }]; } // [END delete_collection] @@ -438,7 +440,7 @@ - (void)serverTimestamp { - (void)serverTimestampOptions { // [START server_timestamp_options] FIRDocumentReference *docRef = - [[self.db collectionWithPath:@"objects"] documentWithPath:@"some-id"]; + [[self.db collectionWithPath:@"objects"] documentWithPath:@"some-id"]; // Perform an update followed by an immediate read without waiting for the update to complete. // Due to the snapshot options we will get two results: one with an estimated timestamp and @@ -459,7 +461,7 @@ - (void)serverTimestampOptions { - (void)simpleTransaction { // [START simple_transaction] FIRDocumentReference *sfReference = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [self.db runTransactionWithBlock:^id (FIRTransaction *transaction, NSError **errorPointer) { FIRDocumentSnapshot *sfDocument = [transaction getDocument:sfReference error:errorPointer]; if (*errorPointer != nil) { return nil; } @@ -531,17 +533,17 @@ - (void)writeBatch { // Set the value of 'NYC' FIRDocumentReference *nycRef = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"NYC"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"NYC"]; [batch setData:@{} forDocument:nycRef]; // Update the population of 'SF' FIRDocumentReference *sfRef = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [batch updateData:@{ @"population": @1000000 } forDocument:sfRef]; // Delete the city 'LA' FIRDocumentReference *laRef = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"LA"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"LA"]; [batch deleteDocument:laRef]; // Commit the batch @@ -603,45 +605,45 @@ - (void)exampleData { } - (void)exampleDataCollectionGroup { - // [START fs_collection_group_query_data_setup] - FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; + // [START fs_collection_group_query_data_setup] + FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; - NSDictionary *data = @{@"name": @"Golden Gate Bridge", @"type": @"bridge"}; - [[[citiesRef documentWithPath:@"SF"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + NSDictionary *data = @{@"name": @"Golden Gate Bridge", @"type": @"bridge"}; + [[[citiesRef documentWithPath:@"SF"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"Legion of Honor", @"type": @"museum"}; - [[[citiesRef documentWithPath:@"SF"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"Legion of Honor", @"type": @"museum"}; + [[[citiesRef documentWithPath:@"SF"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"Griffith Park", @"type": @"park"}; - [[[citiesRef documentWithPath:@"LA"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"Griffith Park", @"type": @"park"}; + [[[citiesRef documentWithPath:@"LA"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"The Getty", @"type": @"museum"}; - [[[citiesRef documentWithPath:@"LA"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"The Getty", @"type": @"museum"}; + [[[citiesRef documentWithPath:@"LA"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"Lincoln Memorial", @"type": @"memorial"}; - [[[citiesRef documentWithPath:@"DC"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"Lincoln Memorial", @"type": @"memorial"}; + [[[citiesRef documentWithPath:@"DC"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"National Air and Space Museum", @"type": @"museum"}; - [[[citiesRef documentWithPath:@"DC"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"National Air and Space Museum", @"type": @"museum"}; + [[[citiesRef documentWithPath:@"DC"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"Ueno Park", @"type": @"park"}; - [[[citiesRef documentWithPath:@"TOK"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"Ueno Park", @"type": @"park"}; + [[[citiesRef documentWithPath:@"TOK"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"National Museum of Nature and Science", @"type": @"museum"}; - [[[citiesRef documentWithPath:@"TOK"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"National Museum of Nature and Science", @"type": @"museum"}; + [[[citiesRef documentWithPath:@"TOK"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"Jingshan Park", @"type": @"park"}; - [[[citiesRef documentWithPath:@"BJ"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + data = @{@"name": @"Jingshan Park", @"type": @"park"}; + [[[citiesRef documentWithPath:@"BJ"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - data = @{@"name": @"Beijing Ancient Observatory", @"type": @"museum"}; - [[[citiesRef documentWithPath:@"BJ"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; - // [END fs_collection_group_query_data_setup] + data = @{@"name": @"Beijing Ancient Observatory", @"type": @"museum"}; + [[[citiesRef documentWithPath:@"BJ"] collectionWithPath:@"landmarks"] addDocumentWithData:data]; + // [END fs_collection_group_query_data_setup] } - (void)getDocument { // [START get_document] FIRDocumentReference *docRef = - [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; + [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) { if (snapshot.exists) { // Document data may be nil if the document exists but has no keys or values. @@ -691,27 +693,27 @@ - (void)customClassGetDocument { - (void)listenDocument { // [START listen_document] [[[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"] - addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) { - if (snapshot == nil) { - NSLog(@"Error fetching document: %@", error); - return; - } - NSLog(@"Current data: %@", snapshot.data); - }]; + addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) { + if (snapshot == nil) { + NSLog(@"Error fetching document: %@", error); + return; + } + NSLog(@"Current data: %@", snapshot.data); + }]; // [END listen_document] } - (void)listenDocumentLocal { // [START listen_document_local] [[[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"] - addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) { - if (snapshot == nil) { - NSLog(@"Error fetching document: %@", error); - return; - } - NSString *source = snapshot.metadata.hasPendingWrites ? @"Local" : @"Server"; - NSLog(@"%@ data: %@", source, snapshot.data); - }]; + addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) { + if (snapshot == nil) { + NSLog(@"Error fetching document: %@", error); + return; + } + NSString *source = snapshot.metadata.hasPendingWrites ? @"Local" : @"Server"; + NSLog(@"%@ data: %@", source, snapshot.data); + }]; // [END listen_document_local] } @@ -719,9 +721,9 @@ - (void)listenWithMetadata { // [START listen_with_metadata] // Listen for metadata changes. [[[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"] - addSnapshotListenerWithIncludeMetadataChanges:YES - listener:^(FIRDocumentSnapshot *snapshot, NSError *error) { - // ... + addSnapshotListenerWithIncludeMetadataChanges:YES + listener:^(FIRDocumentSnapshot *snapshot, NSError *error) { + // ... }]; // [END listen_with_metadata] } @@ -729,98 +731,113 @@ - (void)listenWithMetadata { - (void)getMultiple { // [START get_multiple] [[[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@(YES)] - getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (error != nil) { - NSLog(@"Error getting documents: %@", error); - } else { - for (FIRDocumentSnapshot *document in snapshot.documents) { - NSLog(@"%@ => %@", document.documentID, document.data); - } - } - }]; + getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (error != nil) { + NSLog(@"Error getting documents: %@", error); + } else { + for (FIRDocumentSnapshot *document in snapshot.documents) { + NSLog(@"%@ => %@", document.documentID, document.data); + } + } + }]; // [END get_multiple] } - (void)getMultipleAll { // [START get_multiple_all] [[self.db collectionWithPath:@"cities"] - getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (error != nil) { - NSLog(@"Error getting documents: %@", error); - } else { - for (FIRDocumentSnapshot *document in snapshot.documents) { - NSLog(@"%@ => %@", document.documentID, document.data); - } - } - }]; + getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (error != nil) { + NSLog(@"Error getting documents: %@", error); + } else { + for (FIRDocumentSnapshot *document in snapshot.documents) { + NSLog(@"%@ => %@", document.documentID, document.data); + } + } + }]; // [END get_multiple_all] } +- (void)getMultipleAllSubcollection { + // [START get_multiple_all_subcollection] + [[self.db collectionWithPath:@"cities/SF/landmarks"] + getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (error != nil) { + NSLog(@"Error getting documents: %@", error); + } else { + for (FIRDocumentSnapshot *document in snapshot.documents) { + NSLog(@"%@ => %@", document.documentID, document.data); + } + } + }]; + // [END get_multiple_all_subcollection] +} + - (void)listenMultiple { // [START listen_multiple] [[[self.db collectionWithPath:@"cities"] queryWhereField:@"state" isEqualTo:@"CA"] - addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (snapshot == nil) { - NSLog(@"Error fetching documents: %@", error); - return; - } - NSMutableArray *cities = [NSMutableArray array]; - for (FIRDocumentSnapshot *document in snapshot.documents) { - [cities addObject:document.data[@"name"]]; - } - NSLog(@"Current cities in CA: %@", cities); - }]; + addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (snapshot == nil) { + NSLog(@"Error fetching documents: %@", error); + return; + } + NSMutableArray *cities = [NSMutableArray array]; + for (FIRDocumentSnapshot *document in snapshot.documents) { + [cities addObject:document.data[@"name"]]; + } + NSLog(@"Current cities in CA: %@", cities); + }]; // [END listen_multiple] } - (void)listenDiffs { // [START listen_diffs] [[[self.db collectionWithPath:@"cities"] queryWhereField:@"state" isEqualTo:@"CA"] - addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (snapshot == nil) { - NSLog(@"Error fetching documents: %@", error); - return; - } - for (FIRDocumentChange *diff in snapshot.documentChanges) { - if (diff.type == FIRDocumentChangeTypeAdded) { - NSLog(@"New city: %@", diff.document.data); - } - if (diff.type == FIRDocumentChangeTypeModified) { - NSLog(@"Modified city: %@", diff.document.data); - } - if (diff.type == FIRDocumentChangeTypeRemoved) { - NSLog(@"Removed city: %@", diff.document.data); - } - } - }]; + addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (snapshot == nil) { + NSLog(@"Error fetching documents: %@", error); + return; + } + for (FIRDocumentChange *diff in snapshot.documentChanges) { + if (diff.type == FIRDocumentChangeTypeAdded) { + NSLog(@"New city: %@", diff.document.data); + } + if (diff.type == FIRDocumentChangeTypeModified) { + NSLog(@"Modified city: %@", diff.document.data); + } + if (diff.type == FIRDocumentChangeTypeRemoved) { + NSLog(@"Removed city: %@", diff.document.data); + } + } + }]; // [END listen_diffs] } - (void)listenState { // [START listen_state] [[[self.db collectionWithPath:@"cities"] queryWhereField:@"state" isEqualTo:@"CA"] - addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (snapshot == nil) { - NSLog(@"Error fetching documents: %@", error); - return; - } - for (FIRDocumentChange *diff in snapshot.documentChanges) { - if (diff.type == FIRDocumentChangeTypeAdded) { - NSLog(@"New city: %@", diff.document.data); - } - if (!snapshot.metadata.isFromCache) { - NSLog(@"Synced with server state."); - } - } - }]; + addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (snapshot == nil) { + NSLog(@"Error fetching documents: %@", error); + return; + } + for (FIRDocumentChange *diff in snapshot.documentChanges) { + if (diff.type == FIRDocumentChangeTypeAdded) { + NSLog(@"New city: %@", diff.document.data); + } + if (!snapshot.metadata.isFromCache) { + NSLog(@"Synced with server state."); + } + } + }]; // [END listen_state] } - (void)detachListener { // [START detach_listener] id listener = [[self.db collectionWithPath:@"cities"] - addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { - // ... + addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { + // ... }]; // ... @@ -833,11 +850,11 @@ - (void)detachListener { - (void)handleListenErrors { // [START handle_listen_errors] [[self.db collectionWithPath:@"cities"] - addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (error != nil) { - NSLog(@"Error retreving collection: %@", error); - } - }]; + addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (error != nil) { + NSLog(@"Error retreving collection: %@", error); + } + }]; // [END handle_listen_errors] } @@ -870,7 +887,7 @@ - (void)exampleFilters { - (void)onlyCapitals { // [START only_capitals] FIRQuery *capitalCities = - [[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@YES]; + [[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@YES]; // [END only_capitals] NSLog(@"%@", capitalCities); } @@ -886,9 +903,9 @@ - (void)chainFilters { FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; // [START chain_filters] [[citiesRef queryWhereField:@"state" isEqualTo:@"CO"] - queryWhereField:@"name" isGreaterThanOrEqualTo:@"Denver"]; + queryWhereField:@"name" isGreaterThanOrEqualTo:@"Denver"]; [[citiesRef queryWhereField:@"state" isEqualTo:@"CA"] - queryWhereField:@"population" isLessThan:@1000000]; + queryWhereField:@"population" isLessThan:@1000000]; // [END chain_filters] } @@ -896,9 +913,9 @@ - (void)validRangeFilters { FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; // [START valid_range_filters] [[citiesRef queryWhereField:@"state" isGreaterThanOrEqualTo:@"CA"] - queryWhereField:@"state" isLessThanOrEqualTo:@"IN"]; + queryWhereField:@"state" isLessThanOrEqualTo:@"IN"]; [[citiesRef queryWhereField:@"state" isEqualTo:@"CA"] - queryWhereField:@"population" isGreaterThan:@1000000]; + queryWhereField:@"population" isGreaterThan:@1000000]; // [END valid_range_filters] } @@ -906,7 +923,7 @@ - (void)invalidRangeFilters { FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; // [START invalid_range_filters] [[citiesRef queryWhereField:@"state" isGreaterThanOrEqualTo:@"CA"] - queryWhereField:@"population" isGreaterThan:@1000000]; + queryWhereField:@"population" isGreaterThan:@1000000]; // [END invalid_range_filters] } @@ -935,8 +952,8 @@ - (void)filterAndOrder { FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; // [START filter_and_order] [[[citiesRef queryWhereField:@"population" isGreaterThan:@100000] - queryOrderedByField:@"population"] - queryLimitedTo:2]; + queryOrderedByField:@"population"] + queryLimitedTo:2]; // [END filter_and_order] } @@ -944,7 +961,7 @@ - (void)validFilterAndOrder { FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"]; // [START valid_filter_and_order] [[citiesRef queryWhereField:@"population" isGreaterThan:@100000] - queryOrderedByField:@"population"]; + queryOrderedByField:@"population"]; // [END valid_filter_and_order] } @@ -986,7 +1003,15 @@ - (void)inQueries { - (void)enableOffline { // [START enable_offline] FIRFirestoreSettings *settings = [[FIRFirestoreSettings alloc] init]; - settings.persistenceEnabled = YES; + + // Use memory-only cache + settings.cacheSettings = [[FIRMemoryCacheSettings alloc] + initWithGarbageCollectorSettings:[[FIRMemoryLRUGCSettings alloc] init]]; + + // Use persistent disk cache (default behavior) + // This example uses 100 MB. + settings.cacheSettings = [[FIRPersistentCacheSettings alloc] + initWithSizeBytes:@(100 * 1024 * 1024)]; // Any additional options // ... @@ -1003,21 +1028,21 @@ - (void)listenToOffline { // Listen to metadata updates to receive a server snapshot even if // the data is the same as the cached data. [[[db collectionWithPath:@"cities"] queryWhereField:@"state" isEqualTo:@"CA"] - addSnapshotListenerWithIncludeMetadataChanges:YES - listener:^(FIRQuerySnapshot *snapshot, NSError *error) { - if (snapshot == nil) { - NSLog(@"Error retreiving snapshot: %@", error); - return; - } - for (FIRDocumentChange *diff in snapshot.documentChanges) { - if (diff.type == FIRDocumentChangeTypeAdded) { - NSLog(@"New city: %@", diff.document.data); - } - } + addSnapshotListenerWithIncludeMetadataChanges:YES + listener:^(FIRQuerySnapshot *snapshot, NSError *error) { + if (snapshot == nil) { + NSLog(@"Error retreiving snapshot: %@", error); + return; + } + for (FIRDocumentChange *diff in snapshot.documentChanges) { + if (diff.type == FIRDocumentChangeTypeAdded) { + NSLog(@"New city: %@", diff.document.data); + } + } - NSString *source = snapshot.metadata.isFromCache ? @"local cache" : @"server"; - NSLog(@"Metadata: Data fetched from %@", source); - }]; + NSString *source = snapshot.metadata.isFromCache ? @"local cache" : @"server"; + NSLog(@"Metadata: Data fetched from %@", source); + }]; // [END listen_to_offline] } @@ -1047,14 +1072,14 @@ - (void)simpleCursor { // [START cursor_greater_than] // Get all cities with population over one million, ordered by population. [[[db collectionWithPath:@"cities"] - queryOrderedByField:@"population"] - queryStartingAtValues:@[ @1000000 ]]; + queryOrderedByField:@"population"] + queryStartingAtValues:@[ @1000000 ]]; // [END cursor_greater_than] // [START cursor_less_than] // Get all cities with population less than one million, ordered by population. [[[db collectionWithPath:@"cities"] - queryOrderedByField:@"population"] - queryEndingAtValues:@[ @1000000 ]]; + queryOrderedByField:@"population"] + queryEndingAtValues:@[ @1000000 ]]; // [END cursor_less_than] } @@ -1065,16 +1090,16 @@ - (void)snapshotCursor { // [START snapshot_cursor] [[[db collectionWithPath:@"cities"] documentWithPath:@"SF"] - addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) { - if (snapshot == nil) { - NSLog(@"Error retreiving cities: %@", error); - return; - } - // Get all cities with a population greater than or equal to San Francisco. - FIRQuery *sfSizeOrBigger = [[[db collectionWithPath:@"cities"] - queryOrderedByField:@"population"] - queryStartingAtDocument:snapshot]; - }]; + addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) { + if (snapshot == nil) { + NSLog(@"Error retreiving cities: %@", error); + return; + } + // Get all cities with a population greater than or equal to San Francisco. + FIRQuery *sfSizeOrBigger = [[[db collectionWithPath:@"cities"] + queryOrderedByField:@"population"] + queryStartingAtDocument:snapshot]; + }]; // [END snapshot_cursor] } @@ -1083,8 +1108,8 @@ - (void)paginate { // [START paginate] FIRQuery *first = [[[db collectionWithPath:@"cities"] - queryOrderedByField:@"population"] - queryLimitedTo:25]; + queryOrderedByField:@"population"] + queryLimitedTo:25]; [first addSnapshotListener:^(FIRQuerySnapshot *snapshot, NSError *error) { if (snapshot == nil) { NSLog(@"Error retreiving cities: %@", error); @@ -1096,8 +1121,8 @@ - (void)paginate { // Construct a new query starting after this document, // retreiving the next 25 cities. FIRQuery *next = [[[db collectionWithPath:@"cities"] - queryOrderedByField:@"population"] - queryStartingAfterDocument:lastSnapshot]; + queryOrderedByField:@"population"] + queryStartingAfterDocument:lastSnapshot]; // Use the query for pagination. // ... }]; @@ -1112,67 +1137,248 @@ - (void)multiCursor { // [START multi_cursor] // Will return all Springfields [[[[db collectionWithPath:@"cities"] - queryOrderedByField:@"name"] - queryOrderedByField:@"state"] - queryStartingAtValues:@[ @"Springfield" ]]; + queryOrderedByField:@"name"] + queryOrderedByField:@"state"] + queryStartingAtValues:@[ @"Springfield" ]]; // Will return "Springfield, Missouri" and "Springfield, Wisconsin" [[[[db collectionWithPath:@"cities"] queryOrderedByField:@"name"] - queryOrderedByField:@"state"] - queryStartingAtValues:@[ @"Springfield", @"Missouri" ]]; + queryOrderedByField:@"state"] + queryStartingAtValues:@[ @"Springfield", @"Missouri" ]]; // [END multi_cursor] } - (void)collectionGroupQuery { - // [START fs_collection_group_query] - [[[self.db collectionGroupWithID:@"landmarks"] queryWhereField:@"type" isEqualTo:@"museum"] - getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { - // [START_EXCLUDE] - // [END_EXCLUDE] - }]; - // [END fs_collection_group_query] + // [START fs_collection_group_query] + [[[self.db collectionGroupWithID:@"landmarks"] queryWhereField:@"type" isEqualTo:@"museum"] + getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { + // [START_EXCLUDE] + // [END_EXCLUDE] + }]; + // [END fs_collection_group_query] } - (void)emulatorSettings { - // [START fs_emulator_connect] - FIRFirestoreSettings *settings = [FIRFirestore firestore].settings; - settings.host = @"localhost:8080"; - settings.sslEnabled = false; - [FIRFirestore firestore].settings = settings; - // [END fs_emulator_connect] + // [START fs_emulator_connect] + FIRFirestoreSettings *settings = [FIRFirestore firestore].settings; + settings.host = @"localhost:8080"; + settings.sslEnabled = false; + [FIRFirestore firestore].settings = settings; + // [END fs_emulator_connect] } - (void)countAggregateCollection { - // [START count_aggregate_collection] - FIRCollectionReference *query = [self.db collectionWithPath:@"cities"]; - [query.count aggregationWithSource:FIRAggregateSourceServer - completion:^(FIRAggregateQuerySnapshot *snapshot, - NSError *error) { - if (error != nil) { - NSLog(@"Error fetching count: %@", error); - } else { - NSLog(@"Cities count: %@", snapshot.count); - } - }]; - // [END count_aggregate_collection] + // [START count_aggregate_collection] + FIRCollectionReference *query = [self.db collectionWithPath:@"cities"]; + [query.count aggregationWithSource:FIRAggregateSourceServer + completion:^(FIRAggregateQuerySnapshot *snapshot, + NSError *error) { + if (error != nil) { + NSLog(@"Error fetching count: %@", error); + } else { + NSLog(@"Cities count: %@", snapshot.count); + } + }]; + // [END count_aggregate_collection] } - (void)countAggregateQuery { - // [START count_aggregate_query] - FIRQuery *query = - [[self.db collectionWithPath:@"cities"] - queryWhereField:@"state" - isEqualTo:@"CA"]; - [query.count aggregationWithSource:FIRAggregateSourceServer - completion:^(FIRAggregateQuerySnapshot *snapshot, - NSError *error) { + // [START count_aggregate_query] + FIRQuery *query = + [[self.db collectionWithPath:@"cities"] + queryWhereField:@"state" + isEqualTo:@"CA"]; + [query.count aggregationWithSource:FIRAggregateSourceServer + completion:^(FIRAggregateQuerySnapshot *snapshot, + NSError *error) { + if (error != nil) { + NSLog(@"Error fetching count: %@", error); + } else { + NSLog(@"Cities count: %@", snapshot.count); + } + }]; + // [END count_aggregate_query] +} + +- (void)orQuery { + // [START or_query] + FIRCollectionReference *collection = [self.db collectionWithPath:@"cities"]; + FIRQuery *query = [collection queryWhereFilter:[FIRFilter andFilterWithFilters:@[ + [FIRFilter filterWhereField:@"state" isEqualTo:@"CA"], + [FIRFilter orFilterWithFilters:@[ + [FIRFilter filterWhereField:@"capital" isEqualTo:@YES], + [FIRFilter filterWhereField:@"population" isGreaterThanOrEqualTo:@1000000] + ]] + ]]]; + // [END or_query] +} + +- (void)orQueryDisjunctions { + FIRCollectionReference *collection = [self.db collectionWithPath:@"cities"]; + + // [START one_disjunction] + [collection queryWhereField:@"a" isEqualTo:@1]; + // [END one_disjunction] + + // [START two_disjunctions] + [collection queryWhereFilter:[FIRFilter orFilterWithFilters:@[ + [FIRFilter filterWhereField:@"a" isEqualTo:@1], + [FIRFilter filterWhereField:@"b" isEqualTo:@2] + ]]]; + // [END two_disjunctions] + + // [START four_disjunctions] + [collection queryWhereFilter:[FIRFilter orFilterWithFilters:@[ + [FIRFilter andFilterWithFilters:@[ + [FIRFilter filterWhereField:@"a" isEqualTo:@1], + [FIRFilter filterWhereField:@"c" isEqualTo:@3] + ]], + [FIRFilter andFilterWithFilters:@[ + [FIRFilter filterWhereField:@"a" isEqualTo:@1], + [FIRFilter filterWhereField:@"d" isEqualTo:@4] + ]], + [FIRFilter andFilterWithFilters:@[ + [FIRFilter filterWhereField:@"b" isEqualTo:@2], + [FIRFilter filterWhereField:@"c" isEqualTo:@3] + ]], + [FIRFilter andFilterWithFilters:@[ + [FIRFilter filterWhereField:@"b" isEqualTo:@2], + [FIRFilter filterWhereField:@"d" isEqualTo:@4] + ]], + ]]]; + // [END four_disjunctions] + + // [START four_disjunctions_compact] + [collection queryWhereFilter:[FIRFilter andFilterWithFilters:@[ + [FIRFilter orFilterWithFilters:@[ + [FIRFilter filterWhereField:@"a" isEqualTo:@1], + [FIRFilter filterWhereField:@"b" isEqualTo:@2] + ]], + [FIRFilter orFilterWithFilters:@[ + [FIRFilter filterWhereField:@"c" isEqualTo:@3], + [FIRFilter filterWhereField:@"d" isEqualTo:@4] + ]] + ]]]; + // [END four_disjunctions_compact] + + // [START 20_disjunctions] + [collection queryWhereFilter:[FIRFilter orFilterWithFilters:@[ + [FIRFilter filterWhereField:@"a" in:@[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]], + [FIRFilter filterWhereField:@"b" in:@[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]] + ]]]; + // [END 20_disjunctions] + + // [START 10_disjunctions] + [collection queryWhereFilter:[FIRFilter andFilterWithFilters:@[ + [FIRFilter filterWhereField:@"a" in: @[@1, @2, @3, @4, @5]], + [FIRFilter orFilterWithFilters:@[ + [FIRFilter filterWhereField:@"b" isEqualTo:@2], + [FIRFilter filterWhereField:@"c" isEqualTo:@3] + ]] + ]]]; + // [END 10_disjunctions] +} + +- (void)illegalDisjunctions { + FIRCollectionReference *collection = [self.db collectionWithPath:@"cities"]; + + // [START 20_disjunctions] + [collection queryWhereFilter:[FIRFilter andFilterWithFilters:@[ + [FIRFilter filterWhereField:@"a" in:@[@1, @2, @3, @4, @5]], + [FIRFilter filterWhereField:@"b" in:@[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]] + ]]]; + // [END 20_disjunctions] +} + +- (void)sumAggregateCollection { + // [START sum_aggregate_collection] + FIRQuery *query = [self.db collectionWithPath:@"cities"]; + FIRAggregateQuery *aggregateQuery = [query aggregate:@[ + [FIRAggregateField aggregateFieldForSumOfField:@"population"]]]; + [aggregateQuery aggregationWithSource:FIRAggregateSourceServer + completion:^(FIRAggregateQuerySnapshot *snapshot, + NSError *error) { if (error != nil) { - NSLog(@"Error fetching count: %@", error); + NSLog(@"Error fetching aggregate: %@", error); } else { - NSLog(@"Cities count: %@", snapshot.count); + NSLog(@"Sum: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForSumOfField:@"population"]]); } }]; - // [END count_aggregate_query] + // [END sum_aggregate_collection] +} + +- (void)sumAggregateQuery { + // [START sum_aggregate_query] + FIRQuery *query = [[self.db collectionWithPath:@"cities"] + queryWhereFilter:[FIRFilter filterWhereField:@"capital" isEqualTo:@YES]]; + FIRAggregateQuery *aggregateQuery = [query aggregate:@[ + [FIRAggregateField aggregateFieldForSumOfField:@"population"]]]; + [aggregateQuery aggregationWithSource:FIRAggregateSourceServer + completion:^(FIRAggregateQuerySnapshot *snapshot, + NSError *error) { + if (error != nil) { + NSLog(@"Error fetching aggregate: %@", error); + } else { + NSLog(@"Sum: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForSumOfField:@"population"]]); + } + }]; + // [END sum_aggregate_query] +} + +- (void)averageAggregateCollection { + // [START average_aggregate_collection] + FIRQuery *query = [self.db collectionWithPath:@"cities"]; + FIRAggregateQuery *aggregateQuery = [query aggregate:@[ + [FIRAggregateField aggregateFieldForAverageOfField:@"population"]]]; + [aggregateQuery aggregationWithSource:FIRAggregateSourceServer + completion:^(FIRAggregateQuerySnapshot *snapshot, + NSError *error) { + if (error != nil) { + NSLog(@"Error fetching aggregate: %@", error); + } else { + NSLog(@"Avg: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForAverageOfField:@"population"]]); + } + }]; + // [END average_aggregate_collection] +} + +- (void)averageAggregateQuery { + // [START average_aggregate_query] + FIRQuery *query = [[self.db collectionWithPath:@"cities"] + queryWhereFilter:[FIRFilter filterWhereField:@"capital" isEqualTo:@YES]]; + FIRAggregateQuery *aggregateQuery = [query aggregate:@[ + [FIRAggregateField aggregateFieldForAverageOfField:@"population"]]]; + [aggregateQuery aggregationWithSource:FIRAggregateSourceServer + completion:^(FIRAggregateQuerySnapshot *snapshot, + NSError *error) { + if (error != nil) { + NSLog(@"Error fetching aggregate: %@", error); + } else { + NSLog(@"Avg: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForAverageOfField:@"population"]]); + } + }]; + // [END average_aggregate_query] +} + +- (void)multiAggregateCollection { + // [START multi_aggregate_collection] + FIRQuery *query = [self.db collectionWithPath:@"cities"]; + FIRAggregateQuery *aggregateQuery = [query aggregate:@[ + [FIRAggregateField aggregateFieldForCount], + [FIRAggregateField aggregateFieldForSumOfField:@"population"], + [FIRAggregateField aggregateFieldForAverageOfField:@"population"]]]; + [aggregateQuery aggregationWithSource:FIRAggregateSourceServer + completion:^(FIRAggregateQuerySnapshot *snapshot, + NSError *error) { + if (error != nil) { + NSLog(@"Error fetching aggregate: %@", error); + } else { + NSLog(@"Count: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForCount]]); + NSLog(@"Sum: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForSumOfField:@"population"]]); + NSLog(@"Avg: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForAverageOfField:@"population"]]); + } + }]; + // [END multi_aggregate_collection] } @end diff --git a/firestore/swift/Podfile b/firestore/swift/Podfile index 1d58eb1b..5acf781b 100644 --- a/firestore/swift/Podfile +++ b/firestore/swift/Podfile @@ -1,4 +1,5 @@ -# Uncomment this line to define a global platform for your project +# No longer used since the project migrated to SPM, but this file still exists +# for the GeoFire snippet below. platform :ios, '14.0' target 'firestore-smoketest' do @@ -8,7 +9,6 @@ target 'firestore-smoketest' do # Pods for firestore-smoketest pod 'Firebase/Auth' pod 'Firebase/Firestore' - pod 'FirebaseFirestoreSwift', :git => 'https://github.com/firebase/firebase-ios-sdk.git' # [START geofire_pod] pod 'GeoFire/Utils' diff --git a/firestore/swift/Podfile.lock b/firestore/swift/Podfile.lock deleted file mode 100644 index 0176b14f..00000000 --- a/firestore/swift/Podfile.lock +++ /dev/null @@ -1,786 +0,0 @@ -PODS: - - abseil/algorithm (1.20211102.0): - - abseil/algorithm/algorithm (= 1.20211102.0) - - abseil/algorithm/container (= 1.20211102.0) - - abseil/algorithm/algorithm (1.20211102.0): - - abseil/base/config - - abseil/algorithm/container (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/base (1.20211102.0): - - abseil/base/atomic_hook (= 1.20211102.0) - - abseil/base/base (= 1.20211102.0) - - abseil/base/base_internal (= 1.20211102.0) - - abseil/base/config (= 1.20211102.0) - - abseil/base/core_headers (= 1.20211102.0) - - abseil/base/dynamic_annotations (= 1.20211102.0) - - abseil/base/endian (= 1.20211102.0) - - abseil/base/errno_saver (= 1.20211102.0) - - abseil/base/fast_type_id (= 1.20211102.0) - - abseil/base/log_severity (= 1.20211102.0) - - abseil/base/malloc_internal (= 1.20211102.0) - - abseil/base/pretty_function (= 1.20211102.0) - - abseil/base/raw_logging_internal (= 1.20211102.0) - - abseil/base/spinlock_wait (= 1.20211102.0) - - abseil/base/strerror (= 1.20211102.0) - - abseil/base/throw_delegate (= 1.20211102.0) - - abseil/base/atomic_hook (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/base (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/log_severity - - abseil/base/raw_logging_internal - - abseil/base/spinlock_wait - - abseil/meta/type_traits - - abseil/base/base_internal (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/base/config (1.20211102.0) - - abseil/base/core_headers (1.20211102.0): - - abseil/base/config - - abseil/base/dynamic_annotations (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/errno_saver (1.20211102.0): - - abseil/base/config - - abseil/base/fast_type_id (1.20211102.0): - - abseil/base/config - - abseil/base/log_severity (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/malloc_internal (1.20211102.0): - - abseil/base/base - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/raw_logging_internal - - abseil/base/pretty_function (1.20211102.0) - - abseil/base/raw_logging_internal (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/config - - abseil/base/core_headers - - abseil/base/log_severity - - abseil/base/spinlock_wait (1.20211102.0): - - abseil/base/base_internal - - abseil/base/core_headers - - abseil/base/errno_saver - - abseil/base/strerror (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/errno_saver - - abseil/base/throw_delegate (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/container/common (1.20211102.0): - - abseil/meta/type_traits - - abseil/types/optional - - abseil/container/compressed_tuple (1.20211102.0): - - abseil/utility/utility - - abseil/container/container_memory (1.20211102.0): - - abseil/base/config - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/utility/utility - - abseil/container/fixed_array (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/throw_delegate - - abseil/container/compressed_tuple - - abseil/memory/memory - - abseil/container/flat_hash_map (1.20211102.0): - - abseil/algorithm/container - - abseil/container/container_memory - - abseil/container/hash_function_defaults - - abseil/container/raw_hash_map - - abseil/memory/memory - - abseil/container/hash_function_defaults (1.20211102.0): - - abseil/base/config - - abseil/hash/hash - - abseil/strings/cord - - abseil/strings/strings - - abseil/container/hash_policy_traits (1.20211102.0): - - abseil/meta/type_traits - - abseil/container/hashtable_debug_hooks (1.20211102.0): - - abseil/base/config - - abseil/container/hashtablez_sampler (1.20211102.0): - - abseil/base/base - - abseil/base/core_headers - - abseil/container/have_sse - - abseil/debugging/stacktrace - - abseil/memory/memory - - abseil/profiling/exponential_biased - - abseil/profiling/sample_recorder - - abseil/synchronization/synchronization - - abseil/utility/utility - - abseil/container/have_sse (1.20211102.0) - - abseil/container/inlined_vector (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/core_headers - - abseil/base/throw_delegate - - abseil/container/inlined_vector_internal - - abseil/memory/memory - - abseil/container/inlined_vector_internal (1.20211102.0): - - abseil/base/core_headers - - abseil/container/compressed_tuple - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/types/span - - abseil/container/layout (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/strings/strings - - abseil/types/span - - abseil/utility/utility - - abseil/container/raw_hash_map (1.20211102.0): - - abseil/base/throw_delegate - - abseil/container/container_memory - - abseil/container/raw_hash_set - - abseil/container/raw_hash_set (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/container/common - - abseil/container/compressed_tuple - - abseil/container/container_memory - - abseil/container/hash_policy_traits - - abseil/container/hashtable_debug_hooks - - abseil/container/hashtablez_sampler - - abseil/container/have_sse - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/utility/utility - - abseil/debugging/debugging_internal (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/errno_saver - - abseil/base/raw_logging_internal - - abseil/debugging/demangle_internal (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/debugging/stacktrace (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/debugging/debugging_internal - - abseil/debugging/symbolize (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/malloc_internal - - abseil/base/raw_logging_internal - - abseil/debugging/debugging_internal - - abseil/debugging/demangle_internal - - abseil/strings/strings - - abseil/functional/bind_front (1.20211102.0): - - abseil/base/base_internal - - abseil/container/compressed_tuple - - abseil/meta/type_traits - - abseil/utility/utility - - abseil/functional/function_ref (1.20211102.0): - - abseil/base/base_internal - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/hash/city (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/hash/hash (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/container/fixed_array - - abseil/hash/city - - abseil/hash/low_level_hash - - abseil/meta/type_traits - - abseil/numeric/int128 - - abseil/strings/strings - - abseil/types/optional - - abseil/types/variant - - abseil/utility/utility - - abseil/hash/low_level_hash (1.20211102.0): - - abseil/base/config - - abseil/base/endian - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/memory (1.20211102.0): - - abseil/memory/memory (= 1.20211102.0) - - abseil/memory/memory (1.20211102.0): - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/meta (1.20211102.0): - - abseil/meta/type_traits (= 1.20211102.0) - - abseil/meta/type_traits (1.20211102.0): - - abseil/base/config - - abseil/numeric/bits (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/numeric/int128 (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/numeric/bits - - abseil/numeric/representation (1.20211102.0): - - abseil/base/config - - abseil/profiling/exponential_biased (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/profiling/sample_recorder (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/synchronization/synchronization - - abseil/time/time - - abseil/random/distributions (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/random/internal/distribution_caller - - abseil/random/internal/fast_uniform_bits - - abseil/random/internal/fastmath - - abseil/random/internal/generate_real - - abseil/random/internal/iostream_state_saver - - abseil/random/internal/traits - - abseil/random/internal/uniform_helper - - abseil/random/internal/wide_multiply - - abseil/strings/strings - - abseil/random/internal/distribution_caller (1.20211102.0): - - abseil/base/config - - abseil/base/fast_type_id - - abseil/utility/utility - - abseil/random/internal/fast_uniform_bits (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/random/internal/fastmath (1.20211102.0): - - abseil/numeric/bits - - abseil/random/internal/generate_real (1.20211102.0): - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/random/internal/fastmath - - abseil/random/internal/traits - - abseil/random/internal/iostream_state_saver (1.20211102.0): - - abseil/meta/type_traits - - abseil/numeric/int128 - - abseil/random/internal/nonsecure_base (1.20211102.0): - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/random/internal/pool_urbg - - abseil/random/internal/salted_seed_seq - - abseil/random/internal/seed_material - - abseil/types/optional - - abseil/types/span - - abseil/random/internal/pcg_engine (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/random/internal/fastmath - - abseil/random/internal/iostream_state_saver - - abseil/random/internal/platform (1.20211102.0): - - abseil/base/config - - abseil/random/internal/pool_urbg (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/random/internal/randen - - abseil/random/internal/seed_material - - abseil/random/internal/traits - - abseil/random/seed_gen_exception - - abseil/types/span - - abseil/random/internal/randen (1.20211102.0): - - abseil/base/raw_logging_internal - - abseil/random/internal/platform - - abseil/random/internal/randen_hwaes - - abseil/random/internal/randen_slow - - abseil/random/internal/randen_engine (1.20211102.0): - - abseil/base/endian - - abseil/meta/type_traits - - abseil/random/internal/iostream_state_saver - - abseil/random/internal/randen - - abseil/random/internal/randen_hwaes (1.20211102.0): - - abseil/base/config - - abseil/random/internal/platform - - abseil/random/internal/randen_hwaes_impl - - abseil/random/internal/randen_hwaes_impl (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/numeric/int128 - - abseil/random/internal/platform - - abseil/random/internal/randen_slow (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/numeric/int128 - - abseil/random/internal/platform - - abseil/random/internal/salted_seed_seq (1.20211102.0): - - abseil/container/inlined_vector - - abseil/meta/type_traits - - abseil/random/internal/seed_material - - abseil/types/optional - - abseil/types/span - - abseil/random/internal/seed_material (1.20211102.0): - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/raw_logging_internal - - abseil/random/internal/fast_uniform_bits - - abseil/strings/strings - - abseil/types/optional - - abseil/types/span - - abseil/random/internal/traits (1.20211102.0): - - abseil/base/config - - abseil/random/internal/uniform_helper (1.20211102.0): - - abseil/base/config - - abseil/meta/type_traits - - abseil/random/internal/traits - - abseil/random/internal/wide_multiply (1.20211102.0): - - abseil/base/config - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/random/internal/traits - - abseil/random/random (1.20211102.0): - - abseil/random/distributions - - abseil/random/internal/nonsecure_base - - abseil/random/internal/pcg_engine - - abseil/random/internal/pool_urbg - - abseil/random/internal/randen_engine - - abseil/random/seed_sequences - - abseil/random/seed_gen_exception (1.20211102.0): - - abseil/base/config - - abseil/random/seed_sequences (1.20211102.0): - - abseil/container/inlined_vector - - abseil/random/internal/nonsecure_base - - abseil/random/internal/pool_urbg - - abseil/random/internal/salted_seed_seq - - abseil/random/internal/seed_material - - abseil/random/seed_gen_exception - - abseil/types/span - - abseil/status/status (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/config - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/container/inlined_vector - - abseil/debugging/stacktrace - - abseil/debugging/symbolize - - abseil/functional/function_ref - - abseil/strings/cord - - abseil/strings/str_format - - abseil/strings/strings - - abseil/types/optional - - abseil/status/statusor (1.20211102.0): - - abseil/base/base - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/meta/type_traits - - abseil/status/status - - abseil/strings/strings - - abseil/types/variant - - abseil/utility/utility - - abseil/strings/cord (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/container/fixed_array - - abseil/container/inlined_vector - - abseil/functional/function_ref - - abseil/meta/type_traits - - abseil/strings/cord_internal - - abseil/strings/cordz_functions - - abseil/strings/cordz_info - - abseil/strings/cordz_statistics - - abseil/strings/cordz_update_scope - - abseil/strings/cordz_update_tracker - - abseil/strings/internal - - abseil/strings/str_format - - abseil/strings/strings - - abseil/types/optional - - abseil/strings/cord_internal (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/base/throw_delegate - - abseil/container/compressed_tuple - - abseil/container/inlined_vector - - abseil/container/layout - - abseil/functional/function_ref - - abseil/meta/type_traits - - abseil/strings/strings - - abseil/types/span - - abseil/strings/cordz_functions (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/profiling/exponential_biased - - abseil/strings/cordz_handle (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/synchronization/synchronization - - abseil/strings/cordz_info (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/container/inlined_vector - - abseil/debugging/stacktrace - - abseil/strings/cord_internal - - abseil/strings/cordz_functions - - abseil/strings/cordz_handle - - abseil/strings/cordz_statistics - - abseil/strings/cordz_update_tracker - - abseil/synchronization/synchronization - - abseil/types/span - - abseil/strings/cordz_statistics (1.20211102.0): - - abseil/base/config - - abseil/strings/cordz_update_tracker - - abseil/strings/cordz_update_scope (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/strings/cord_internal - - abseil/strings/cordz_info - - abseil/strings/cordz_update_tracker - - abseil/strings/cordz_update_tracker (1.20211102.0): - - abseil/base/config - - abseil/strings/internal (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/meta/type_traits - - abseil/strings/str_format (1.20211102.0): - - abseil/strings/str_format_internal - - abseil/strings/str_format_internal (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/functional/function_ref - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/numeric/representation - - abseil/strings/strings - - abseil/types/optional - - abseil/types/span - - abseil/strings/strings (1.20211102.0): - - abseil/base/base - - abseil/base/config - - abseil/base/core_headers - - abseil/base/endian - - abseil/base/raw_logging_internal - - abseil/base/throw_delegate - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/numeric/bits - - abseil/numeric/int128 - - abseil/strings/internal - - abseil/synchronization/graphcycles_internal (1.20211102.0): - - abseil/base/base - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/malloc_internal - - abseil/base/raw_logging_internal - - abseil/synchronization/kernel_timeout_internal (1.20211102.0): - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/time/time - - abseil/synchronization/synchronization (1.20211102.0): - - abseil/base/atomic_hook - - abseil/base/base - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/base/dynamic_annotations - - abseil/base/malloc_internal - - abseil/base/raw_logging_internal - - abseil/debugging/stacktrace - - abseil/debugging/symbolize - - abseil/synchronization/graphcycles_internal - - abseil/synchronization/kernel_timeout_internal - - abseil/time/time - - abseil/time (1.20211102.0): - - abseil/time/internal (= 1.20211102.0) - - abseil/time/time (= 1.20211102.0) - - abseil/time/internal (1.20211102.0): - - abseil/time/internal/cctz (= 1.20211102.0) - - abseil/time/internal/cctz (1.20211102.0): - - abseil/time/internal/cctz/civil_time (= 1.20211102.0) - - abseil/time/internal/cctz/time_zone (= 1.20211102.0) - - abseil/time/internal/cctz/civil_time (1.20211102.0): - - abseil/base/config - - abseil/time/internal/cctz/time_zone (1.20211102.0): - - abseil/base/config - - abseil/time/internal/cctz/civil_time - - abseil/time/time (1.20211102.0): - - abseil/base/base - - abseil/base/core_headers - - abseil/base/raw_logging_internal - - abseil/numeric/int128 - - abseil/strings/strings - - abseil/time/internal/cctz/civil_time - - abseil/time/internal/cctz/time_zone - - abseil/types (1.20211102.0): - - abseil/types/any (= 1.20211102.0) - - abseil/types/bad_any_cast (= 1.20211102.0) - - abseil/types/bad_any_cast_impl (= 1.20211102.0) - - abseil/types/bad_optional_access (= 1.20211102.0) - - abseil/types/bad_variant_access (= 1.20211102.0) - - abseil/types/compare (= 1.20211102.0) - - abseil/types/optional (= 1.20211102.0) - - abseil/types/span (= 1.20211102.0) - - abseil/types/variant (= 1.20211102.0) - - abseil/types/any (1.20211102.0): - - abseil/base/config - - abseil/base/core_headers - - abseil/base/fast_type_id - - abseil/meta/type_traits - - abseil/types/bad_any_cast - - abseil/utility/utility - - abseil/types/bad_any_cast (1.20211102.0): - - abseil/base/config - - abseil/types/bad_any_cast_impl - - abseil/types/bad_any_cast_impl (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/types/bad_optional_access (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/types/bad_variant_access (1.20211102.0): - - abseil/base/config - - abseil/base/raw_logging_internal - - abseil/types/compare (1.20211102.0): - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/types/optional (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/memory/memory - - abseil/meta/type_traits - - abseil/types/bad_optional_access - - abseil/utility/utility - - abseil/types/span (1.20211102.0): - - abseil/algorithm/algorithm - - abseil/base/core_headers - - abseil/base/throw_delegate - - abseil/meta/type_traits - - abseil/types/variant (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/base/core_headers - - abseil/meta/type_traits - - abseil/types/bad_variant_access - - abseil/utility/utility - - abseil/utility/utility (1.20211102.0): - - abseil/base/base_internal - - abseil/base/config - - abseil/meta/type_traits - - BoringSSL-GRPC (0.0.24): - - BoringSSL-GRPC/Implementation (= 0.0.24) - - BoringSSL-GRPC/Interface (= 0.0.24) - - BoringSSL-GRPC/Implementation (0.0.24): - - BoringSSL-GRPC/Interface (= 0.0.24) - - BoringSSL-GRPC/Interface (0.0.24) - - Firebase/Auth (10.2.0): - - Firebase/CoreOnly - - FirebaseAuth (~> 10.2.0) - - Firebase/CoreOnly (10.2.0): - - FirebaseCore (= 10.2.0) - - Firebase/Firestore (10.2.0): - - Firebase/CoreOnly - - FirebaseFirestore (~> 10.2.0) - - FirebaseAuth (10.2.0): - - FirebaseCore (~> 10.0) - - GoogleUtilities/AppDelegateSwizzler (~> 7.8) - - GoogleUtilities/Environment (~> 7.8) - - GTMSessionFetcher/Core (< 4.0, >= 2.1) - - FirebaseCore (10.2.0): - - FirebaseCoreInternal (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/Logger (~> 7.8) - - FirebaseCoreExtension (10.2.0): - - FirebaseCore (~> 10.0) - - FirebaseCoreInternal (10.2.0): - - "GoogleUtilities/NSData+zlib (~> 7.8)" - - FirebaseFirestore (10.2.0): - - abseil/algorithm (~> 1.20211102.0) - - abseil/base (~> 1.20211102.0) - - abseil/container/flat_hash_map (~> 1.20211102.0) - - abseil/memory (~> 1.20211102.0) - - abseil/meta (~> 1.20211102.0) - - abseil/strings/strings (~> 1.20211102.0) - - abseil/time (~> 1.20211102.0) - - abseil/types (~> 1.20211102.0) - - FirebaseCore (~> 10.0) - - "gRPC-C++ (~> 1.44.0)" - - leveldb-library (~> 1.22) - - nanopb (< 2.30910.0, >= 2.30908.0) - - FirebaseFirestoreSwift (10.3.0): - - FirebaseCore (~> 10.0) - - FirebaseCoreExtension (~> 10.0) - - FirebaseFirestore (~> 10.0) - - FirebaseSharedSwift (~> 10.0) - - FirebaseSharedSwift (10.2.0) - - GeoFire/Utils (4.3.0) - - GoogleUtilities/AppDelegateSwizzler (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/Logger - - GoogleUtilities/Network - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/Network (7.10.0): - - GoogleUtilities/Logger - - "GoogleUtilities/NSData+zlib" - - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GoogleUtilities/Reachability (7.10.0): - - GoogleUtilities/Logger - - "gRPC-C++ (1.44.0)": - - "gRPC-C++/Implementation (= 1.44.0)" - - "gRPC-C++/Interface (= 1.44.0)" - - "gRPC-C++/Implementation (1.44.0)": - - abseil/base/base (= 1.20211102.0) - - abseil/base/core_headers (= 1.20211102.0) - - abseil/container/flat_hash_map (= 1.20211102.0) - - abseil/container/inlined_vector (= 1.20211102.0) - - abseil/functional/bind_front (= 1.20211102.0) - - abseil/hash/hash (= 1.20211102.0) - - abseil/memory/memory (= 1.20211102.0) - - abseil/random/random (= 1.20211102.0) - - abseil/status/status (= 1.20211102.0) - - abseil/status/statusor (= 1.20211102.0) - - abseil/strings/cord (= 1.20211102.0) - - abseil/strings/str_format (= 1.20211102.0) - - abseil/strings/strings (= 1.20211102.0) - - abseil/synchronization/synchronization (= 1.20211102.0) - - abseil/time/time (= 1.20211102.0) - - abseil/types/optional (= 1.20211102.0) - - abseil/types/variant (= 1.20211102.0) - - abseil/utility/utility (= 1.20211102.0) - - "gRPC-C++/Interface (= 1.44.0)" - - gRPC-Core (= 1.44.0) - - "gRPC-C++/Interface (1.44.0)" - - gRPC-Core (1.44.0): - - gRPC-Core/Implementation (= 1.44.0) - - gRPC-Core/Interface (= 1.44.0) - - gRPC-Core/Implementation (1.44.0): - - abseil/base/base (= 1.20211102.0) - - abseil/base/core_headers (= 1.20211102.0) - - abseil/container/flat_hash_map (= 1.20211102.0) - - abseil/container/inlined_vector (= 1.20211102.0) - - abseil/functional/bind_front (= 1.20211102.0) - - abseil/hash/hash (= 1.20211102.0) - - abseil/memory/memory (= 1.20211102.0) - - abseil/random/random (= 1.20211102.0) - - abseil/status/status (= 1.20211102.0) - - abseil/status/statusor (= 1.20211102.0) - - abseil/strings/cord (= 1.20211102.0) - - abseil/strings/str_format (= 1.20211102.0) - - abseil/strings/strings (= 1.20211102.0) - - abseil/synchronization/synchronization (= 1.20211102.0) - - abseil/time/time (= 1.20211102.0) - - abseil/types/optional (= 1.20211102.0) - - abseil/types/variant (= 1.20211102.0) - - abseil/utility/utility (= 1.20211102.0) - - BoringSSL-GRPC (= 0.0.24) - - gRPC-Core/Interface (= 1.44.0) - - Libuv-gRPC (= 0.0.10) - - gRPC-Core/Interface (1.44.0) - - GTMSessionFetcher/Core (3.0.0) - - leveldb-library (1.22.1) - - Libuv-gRPC (0.0.10): - - Libuv-gRPC/Implementation (= 0.0.10) - - Libuv-gRPC/Interface (= 0.0.10) - - Libuv-gRPC/Implementation (0.0.10): - - Libuv-gRPC/Interface (= 0.0.10) - - Libuv-gRPC/Interface (0.0.10) - - nanopb (2.30909.0): - - nanopb/decode (= 2.30909.0) - - nanopb/encode (= 2.30909.0) - - nanopb/decode (2.30909.0) - - nanopb/encode (2.30909.0) - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - Firebase/Auth - - Firebase/Firestore - - FirebaseFirestoreSwift (from `https://github.com/firebase/firebase-ios-sdk.git`) - - GeoFire/Utils - -SPEC REPOS: - trunk: - - abseil - - BoringSSL-GRPC - - Firebase - - FirebaseAuth - - FirebaseCore - - FirebaseCoreExtension - - FirebaseCoreInternal - - FirebaseFirestore - - FirebaseSharedSwift - - GeoFire - - GoogleUtilities - - "gRPC-C++" - - gRPC-Core - - GTMSessionFetcher - - leveldb-library - - Libuv-gRPC - - nanopb - - PromisesObjC - -EXTERNAL SOURCES: - FirebaseFirestoreSwift: - :git: https://github.com/firebase/firebase-ios-sdk.git - -CHECKOUT OPTIONS: - FirebaseFirestoreSwift: - :commit: d419ed6079af7dc53ef692e387e0c31bcf232275 - :git: https://github.com/firebase/firebase-ios-sdk.git - -SPEC CHECKSUMS: - abseil: ebe5b5529fb05d93a8bdb7951607be08b7fa71bc - BoringSSL-GRPC: 3175b25143e648463a56daeaaa499c6cb86dad33 - Firebase: a3ea7eba4382afd83808376edb99acdaff078dcf - FirebaseAuth: 08e7739244eeae5216d0a3f8d9f16a76be9c252e - FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1 - FirebaseCoreExtension: d08b424832917cf13612021574399afbbedffeef - FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f - FirebaseFirestore: bda7a1ca8c19319a2acd2761cd4b962022c1d5ea - FirebaseFirestoreSwift: 55098402529ce59ba54a2ce1ad5798ae1ba563ef - FirebaseSharedSwift: a160b39d4ce77be922b3d6ff009099c7294e36e5 - GeoFire: c34927b5c81ab614f611c79aa8d074cfa9780f07 - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - "gRPC-C++": 9675f953ace2b3de7c506039d77be1f2e77a8db2 - gRPC-Core: 943e491cb0d45598b0b0eb9e910c88080369290b - GTMSessionFetcher: c1edebe64e9fb4e8f6415d018edf1fd3eac074a1 - leveldb-library: 50c7b45cbd7bf543c81a468fe557a16ae3db8729 - Libuv-gRPC: 55e51798e14ef436ad9bc45d12d43b77b49df378 - nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 97272481fd29bdcf2f666d99fa188fa8f4e80c39 - -COCOAPODS: 1.11.3 diff --git a/firestore/swift/firestore-smoketest.xcodeproj/project.pbxproj b/firestore/swift/firestore-smoketest.xcodeproj/project.pbxproj index 8367394b..ea360fd5 100644 --- a/firestore/swift/firestore-smoketest.xcodeproj/project.pbxproj +++ b/firestore/swift/firestore-smoketest.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -17,6 +17,9 @@ 3EABFB2D1E254C8F00F4BBED /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 3EABFB2B1E254C8F00F4BBED /* LaunchScreen.storyboard */; }; 3EABFB381E254C8F00F4BBED /* firestore_smoketestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EABFB371E254C8F00F4BBED /* firestore_smoketestTests.swift */; }; 3EABFB431E254C8F00F4BBED /* firestore_smoketestUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EABFB421E254C8F00F4BBED /* firestore_smoketestUITests.swift */; }; + 8D7951A32D28AC82000FD694 /* FirebaseAuth in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951A22D28AC82000FD694 /* FirebaseAuth */; }; + 8D7951A52D28AC82000FD694 /* FirebaseFirestore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951A42D28AC82000FD694 /* FirebaseFirestore */; }; + 8D7951A82D28ADBE000FD694 /* GeoFireUtils in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951A72D28ADBE000FD694 /* GeoFireUtils */; }; 8D864B17260D3947008E85B3 /* SolutionBundles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D864B16260D3947008E85B3 /* SolutionBundles.swift */; }; 8D864B35260D55C1008E85B3 /* SolutionGeoPointViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DFC116F258A2B8E00D080CB /* SolutionGeoPointViewController.swift */; }; 8DA9B4AB201165C800EC29CD /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 8DA9B4AA201165C800EC29CD /* GoogleService-Info.plist */; }; @@ -66,6 +69,9 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951A32D28AC82000FD694 /* FirebaseAuth in Frameworks */, + 8D7951A82D28ADBE000FD694 /* GeoFireUtils in Frameworks */, + 8D7951A52D28AC82000FD694 /* FirebaseFirestore in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -92,8 +98,8 @@ 3EABFB211E254C8F00F4BBED /* firestore-smoketest */, 3EABFB361E254C8F00F4BBED /* firestore-smoketestTests */, 3EABFB411E254C8F00F4BBED /* firestore-smoketestUITests */, + 8D7951A12D28AC82000FD694 /* Frameworks */, 3EABFB201E254C8F00F4BBED /* Products */, - 89B479BF7A6DFFF64734BB51 /* Pods */, ); sourceTree = ""; }; @@ -144,11 +150,11 @@ path = "firestore-smoketestUITests"; sourceTree = ""; }; - 89B479BF7A6DFFF64734BB51 /* Pods */ = { + 8D7951A12D28AC82000FD694 /* Frameworks */ = { isa = PBXGroup; children = ( ); - path = Pods; + name = Frameworks; sourceTree = ""; }; /* End PBXGroup section */ @@ -213,8 +219,9 @@ 3EABFB171E254C8E00F4BBED /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 0800; - LastUpgradeCheck = 1000; + LastUpgradeCheck = 1610; ORGANIZATIONNAME = Firebase; TargetAttributes = { 3EABFB1E1E254C8E00F4BBED = { @@ -238,14 +245,17 @@ }; buildConfigurationList = 3EABFB1A1E254C8E00F4BBED /* Build configuration list for PBXProject "firestore-smoketest" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( - English, en, Base, ); mainGroup = 3EABFB161E254C8E00F4BBED; + packageReferences = ( + 8D7951A02D28AC75000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + 8D7951A62D28ADAE000FD694 /* XCRemoteSwiftPackageReference "geofire-objc" */, + ); productRefGroup = 3EABFB201E254C8F00F4BBED /* Products */; projectDirPath = ""; projectRoot = ""; @@ -375,6 +385,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -386,6 +397,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -400,7 +412,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -434,6 +446,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -445,6 +458,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -453,10 +467,11 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -469,7 +484,10 @@ "GCC_WARN_64_TO_32_BIT_CONVERSION[arch=*64]" = YES; INFOPLIST_FILE = "firestore-smoketest/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.google.firebase.firestore-smoketest"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.0; @@ -484,7 +502,10 @@ "GCC_WARN_64_TO_32_BIT_CONVERSION[arch=*64]" = YES; INFOPLIST_FILE = "firestore-smoketest/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 14.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.google.firebase.firestore-smoketest"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.0; @@ -495,10 +516,13 @@ 3EABFB4B1E254C8F00F4BBED /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = "firestore-smoketestTests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.google.firebase.firestore-smoketestTests"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.0; @@ -509,10 +533,13 @@ 3EABFB4C1E254C8F00F4BBED /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = "firestore-smoketestTests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.google.firebase.firestore-smoketestTests"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.0; @@ -523,9 +550,12 @@ 3EABFB4E1E254C8F00F4BBED /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; INFOPLIST_FILE = "firestore-smoketestUITests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.google.firebase.firestore-smoketestUITests"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.0; @@ -536,9 +566,12 @@ 3EABFB4F1E254C8F00F4BBED /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; INFOPLIST_FILE = "firestore-smoketestUITests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "com.google.firebase.firestore-smoketestUITests"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.0; @@ -586,6 +619,43 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7951A02D28AC75000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; + 8D7951A62D28ADAE000FD694 /* XCRemoteSwiftPackageReference "geofire-objc" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/geofire-objc"; + requirement = { + branch = master; + kind = branch; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7951A22D28AC82000FD694 /* FirebaseAuth */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A02D28AC75000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAuth; + }; + 8D7951A42D28AC82000FD694 /* FirebaseFirestore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A02D28AC75000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseFirestore; + }; + 8D7951A72D28ADBE000FD694 /* GeoFireUtils */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A62D28ADAE000FD694 /* XCRemoteSwiftPackageReference "geofire-objc" */; + productName = GeoFireUtils; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 3EABFB171E254C8E00F4BBED /* Project object */; } diff --git a/firestore/swift/firestore-smoketest/SolutionAggregationViewController.swift b/firestore/swift/firestore-smoketest/SolutionAggregationViewController.swift index c8e02157..bd23e3a1 100644 --- a/firestore/swift/firestore-smoketest/SolutionAggregationViewController.swift +++ b/firestore/swift/firestore-smoketest/SolutionAggregationViewController.swift @@ -21,83 +21,80 @@ import FirebaseFirestore class SolutionAggregationViewController: UIViewController { - var db: Firestore! - - // [START restaurant_struct] - struct Restaurant { - - let name: String - let avgRating: Float - let numRatings: Int - - init(name: String, avgRating: Float, numRatings: Int) { - self.name = name - self.avgRating = avgRating - self.numRatings = numRatings - } - - } - - let arinell = Restaurant(name: "Arinell Pizza", avgRating: 4.65, numRatings: 683) - // [END restaurant_struct] - - struct Rating { - let rating: Float + var db: Firestore! + + // [START restaurant_struct] + struct Restaurant { + + let name: String + let avgRating: Float + let numRatings: Int + + } + + let arinell = Restaurant(name: "Arinell Pizza", avgRating: 4.65, numRatings: 683) + // [END restaurant_struct] + + struct Rating { + let rating: Float + } + + override func viewDidLoad() { + super.viewDidLoad() + db = Firestore.firestore() + } + + func getRatingsSubcollection() async { + // [START get_ratings_subcollection] + do { + let snapshot = try await db.collection("restaurants") + .document("arinell-pizza") + .collection("ratings") + .getDocuments() + print(snapshot) + } catch { + print(error) } - - override func viewDidLoad() { - super.viewDidLoad() - db = Firestore.firestore() - } - - func getRatingsSubcollection() { - // [START get_ratings_subcollection] - db.collection("restaurants") - .document("arinell-pizza") - .collection("ratings") - .getDocuments() { (querySnapshot, err) in - - // ... - + // [END get_ratings_subcollection] + } + + // [START add_rating_transaction] + func addRatingTransaction(restaurantRef: DocumentReference, rating: Float) async { + let ratingRef: DocumentReference = restaurantRef.collection("ratings").document() + + do { + let _ = try await db.runTransaction({ (transaction, errorPointer) -> Any? in + do { + let restaurantDocument = try transaction.getDocument(restaurantRef).data() + guard var restaurantData = restaurantDocument else { return nil } + + // Compute new number of ratings + let numRatings = restaurantData["numRatings"] as! Int + let newNumRatings = numRatings + 1 + + // Compute new average rating + let avgRating = restaurantData["avgRating"] as! Float + let oldRatingTotal = avgRating * Float(numRatings) + let newAvgRating = (oldRatingTotal + rating) / Float(newNumRatings) + + // Set new restaurant info + restaurantData["numRatings"] = newNumRatings + restaurantData["avgRating"] = newAvgRating + + // Commit to Firestore + transaction.setData(restaurantData, forDocument: restaurantRef) + transaction.setData(["rating": rating], forDocument: ratingRef) + } catch { + // Error getting restaurant data + // ... } - // [END get_ratings_subcollection] - } - // [START add_rating_transaction] - func addRatingTransaction(restaurantRef: DocumentReference, rating: Float) { - let ratingRef: DocumentReference = restaurantRef.collection("ratings").document() - - db.runTransaction({ (transaction, errorPointer) -> Any? in - do { - let restaurantDocument = try transaction.getDocument(restaurantRef).data() - guard var restaurantData = restaurantDocument else { return nil } - - // Compute new number of ratings - let numRatings = restaurantData["numRatings"] as! Int - let newNumRatings = numRatings + 1 - - // Compute new average rating - let avgRating = restaurantData["avgRating"] as! Float - let oldRatingTotal = avgRating * Float(numRatings) - let newAvgRating = (oldRatingTotal + rating) / Float(newNumRatings) - - // Set new restaurant info - restaurantData["numRatings"] = newNumRatings - restaurantData["avgRating"] = newAvgRating - - // Commit to Firestore - transaction.setData(restaurantData, forDocument: restaurantRef) - transaction.setData(["rating": rating], forDocument: ratingRef) - } catch { - // Error getting restaurant data - // ... - } - - return nil - }) { (object, err) in - // ... - } + return nil + }) + } catch { + // ... } - // [END add_rating_transaction] + } + // [END add_rating_transaction] } diff --git a/firestore/swift/firestore-smoketest/SolutionArraysViewController.swift b/firestore/swift/firestore-smoketest/SolutionArraysViewController.swift index 4f51b610..aece8f89 100644 --- a/firestore/swift/firestore-smoketest/SolutionArraysViewController.swift +++ b/firestore/swift/firestore-smoketest/SolutionArraysViewController.swift @@ -21,94 +21,86 @@ import FirebaseFirestore class SolutionArraysViewController: UIViewController { - var db: Firestore! - - override func viewDidLoad() { - super.viewDidLoad() - db = Firestore.firestore() - } - - func queryInCategory() { - // [START query_in_category] - db.collection("posts") - .whereField("categories.cats", isEqualTo: true) - .getDocuments() { (querySnapshot, err) in - - // ... - - } - // [END query_in_category] - } - - func queryInCategoryTimestamp() { - // [START query_in_category_timestamp_invalid] - db.collection("posts") - .whereField("categories.cats", isEqualTo: true) - .order(by: "timestamp") - // [END query_in_category_timestamp_invalid] - - // [START query_in_category_timestamp] - db.collection("posts") - .whereField("categories.cats", isGreaterThan: 0) - .order(by: "categories.cats") - // [END query_in_category_timestamp] + var db: Firestore! + + override func viewDidLoad() { + super.viewDidLoad() + db = Firestore.firestore() + } + + func queryInCategory() async { + // [START query_in_category] + do { + let querySnapshot = try await db.collection("posts") + .whereField("categories.cats", isEqualTo: true) + .getDocuments() + // Do something with the snapshot + print(querySnapshot) + } catch { + print("Error: \(error)") } - - // [START post_with_array] - struct PostArray { - - let title: String - let categories: [String] - - init(title: String, categories: [String]) { - self.title = title - self.categories = categories - } - + // [END query_in_category] + } + + func queryInCategoryTimestamp() { + // [START query_in_category_timestamp_invalid] + db.collection("posts") + .whereField("categories.cats", isEqualTo: true) + .order(by: "timestamp") + // [END query_in_category_timestamp_invalid] + + // [START query_in_category_timestamp] + db.collection("posts") + .whereField("categories.cats", isGreaterThan: 0) + .order(by: "categories.cats") + // [END query_in_category_timestamp] + } + + // [START post_with_array] + struct PostArray { + + let title: String + let categories: [String] + + init(title: String, categories: [String]) { + self.title = title + self.categories = categories } - let myArrayPost = PostArray(title: "My great post", - categories: ["technology", "opinion", "cats"]) - // [END post_with_array] + } - // [START post_with_dict] - struct PostDict { + let myArrayPost = PostArray(title: "My great post", + categories: ["technology", "opinion", "cats"]) + // [END post_with_array] - let title: String - let categories: [String: Bool] + // [START post_with_dict] + struct PostDict { - init(title: String, categories: [String: Bool]) { - self.title = title - self.categories = categories - } + let title: String + let categories: [String: Bool] - } - - let post = PostDict(title: "My great post", categories: [ - "technology": true, - "opinion": true, - "cats": true - ]) - // [END post_with_dict] + } - // [START post_with_dict_advanced] - struct PostDictAdvanced { + let post = PostDict(title: "My great post", categories: [ + "technology": true, + "opinion": true, + "cats": true + ]) + // [END post_with_dict] - let title: String - let categories: [String: UInt64] + // [START post_with_dict_advanced] + struct PostDictAdvanced { - init(title: String, categories: [String: UInt64]) { - self.title = title - self.categories = categories - } + let title: String + let categories: [String: UInt64] - } + } - let dictPost = PostDictAdvanced(title: "My great post", categories: [ - "technology": 1502144665, - "opinion": 1502144665, - "cats": 1502144665 - ]) - // [END post_with_dict_advanced] + let dictPost = PostDictAdvanced(title: "My great post", categories: [ + "technology": 1502144665, + "opinion": 1502144665, + "cats": 1502144665 + ]) + // [END post_with_dict_advanced] } diff --git a/firestore/swift/firestore-smoketest/SolutionBundles.swift b/firestore/swift/firestore-smoketest/SolutionBundles.swift index ae678321..39a839a3 100644 --- a/firestore/swift/firestore-smoketest/SolutionBundles.swift +++ b/firestore/swift/firestore-smoketest/SolutionBundles.swift @@ -26,93 +26,43 @@ class SolutionBundles { userInfo: [NSLocalizedFailureReasonErrorKey: reason]) } - // Loads a remote bundle from the provided url. func fetchRemoteBundle(for firestore: Firestore, - from url: URL, - completion: @escaping ((Result) -> ())) { + from url: URL) async throws -> LoadBundleTaskProgress { guard let inputStream = InputStream(url: url) else { let error = self.bundleLoadError(reason: "Unable to create stream from the given url: \(url)") - completion(.failure(error)) - return + throw error } - // The return value of this function is ignored, but can be used for more granular - // bundle load observation. - let _ = firestore.loadBundle(inputStream) { (progress, error) in - switch (progress, error) { - - case (.some(let value), .none): - if value.state == .success { - completion(.success(value)) - } else { - let concreteError = self.bundleLoadError( - reason: "Expected bundle load to be completed, but got \(value.state) instead" - ) - completion(.failure(concreteError)) - } - - case (.none, .some(let concreteError)): - completion(.failure(concreteError)) - - case (.none, .none): - let concreteError = self.bundleLoadError(reason: "Operation failed, but returned no error.") - completion(.failure(concreteError)) - - case (.some(let value), .some(let concreteError)): - let concreteError = self.bundleLoadError( - reason: "Operation returned error \(concreteError) with nonnull progress: \(value)" - ) - completion(.failure(concreteError)) - } - } + return try await firestore.loadBundle(inputStream) } // Fetches a specific named query from the provided bundle. func loadQuery(named queryName: String, fromRemoteBundle bundleURL: URL, - with store: Firestore, - completion: @escaping ((Result) -> ())) { - fetchRemoteBundle(for: store, - from: bundleURL) { (result) in - switch result { - case .success: - store.getQuery(named: queryName) { query in - if let query = query { - completion(.success(query)) - } else { - completion( - .failure( - self.bundleLoadError(reason: "Could not find query named \(queryName)") - ) - ) - } - } - - case .failure(let error): - completion(.failure(error)) - } + with store: Firestore) async throws -> Query { + let _ = try await fetchRemoteBundle(for: store, from: bundleURL) + if let query = await store.getQuery(named: queryName) { + return query + } else { + throw bundleLoadError(reason: "Could not find query named \(queryName)") } } // Load a query and fetch its results from a bundle. - func runStoriesQuery() { + func runStoriesQuery() async { let queryName = "latest-stories-query" let firestore = Firestore.firestore() let remoteBundle = URL(string: "https://example.com/createBundle")! - loadQuery(named: queryName, - fromRemoteBundle: remoteBundle, - with: firestore) { (result) in - switch result { - case .failure(let error): - print(error) - case .success(let query): - query.getDocuments { (snapshot, error) in - - // handle query results - - } - } + do { + let query = try await loadQuery(named: queryName, + fromRemoteBundle: remoteBundle, + with: firestore) + let snapshot = try await query.getDocuments() + print(snapshot) + // handle query results + } catch { + print(error) } } // [END fs_bundle_load] @@ -132,12 +82,18 @@ class SolutionBundles { // [END fs_simple_bundle_load] // [START fs_named_query] - func runNamedQuery() { + func runNamedQuery() async { let firestore = Firestore.firestore() - firestore.getQuery(named: "coll-query") { query in - query?.getDocuments { (snapshot, error) in - // ... + let queryName = "coll-query" + do { + guard let query = await firestore.getQuery(named: queryName) else { + throw bundleLoadError(reason: "Could not find query named \(queryName)") } + let snapshot = try await query.getDocuments() + print(snapshot) + // ... + } catch { + print(error) } } // [END fs_named_query] diff --git a/firestore/swift/firestore-smoketest/SolutionCountersViewController.swift b/firestore/swift/firestore-smoketest/SolutionCountersViewController.swift index 85809860..ab8df095 100644 --- a/firestore/swift/firestore-smoketest/SolutionCountersViewController.swift +++ b/firestore/swift/firestore-smoketest/SolutionCountersViewController.swift @@ -21,71 +21,72 @@ import FirebaseFirestore class SolutionCountersController: UIViewController { - var db: Firestore! + var db: Firestore! - override func viewDidLoad() { - super.viewDidLoad() - db = Firestore.firestore() - } + override func viewDidLoad() { + super.viewDidLoad() + db = Firestore.firestore() + } - // [START counter_structs] - // counters/${ID} - struct Counter { - let numShards: Int + // [START counter_structs] + // counters/${ID} + struct Counter { + let numShards: Int - init(numShards: Int) { - self.numShards = numShards - } + init(numShards: Int) { + self.numShards = numShards } + } - // counters/${ID}/shards/${NUM} - struct Shard { - let count: Int + // counters/${ID}/shards/${NUM} + struct Shard { + let count: Int - init(count: Int) { - self.count = count - } + init(count: Int) { + self.count = count } - // [END counter_structs] + } + // [END counter_structs] - // [START create_counter] - func createCounter(ref: DocumentReference, numShards: Int) { - ref.setData(["numShards": numShards]){ (err) in - for i in 0...numShards { - ref.collection("shards").document(String(i)).setData(["count": 0]) - } - } + // [START create_counter] + func createCounter(ref: DocumentReference, numShards: Int) async { + do { + try await ref.setData(["numShards": numShards]) + for i in 0...numShards { + try await ref.collection("shards").document(String(i)).setData(["count": 0]) + } + } catch { + // ... } - // [END create_counter] + } + // [END create_counter] - // [START increment_counter] - func incrementCounter(ref: DocumentReference, numShards: Int) { - // Select a shard of the counter at random - let shardId = Int(arc4random_uniform(UInt32(numShards))) - let shardRef = ref.collection("shards").document(String(shardId)) + // [START increment_counter] + func incrementCounter(ref: DocumentReference, numShards: Int) { + // Select a shard of the counter at random + let shardId = Int(arc4random_uniform(UInt32(numShards))) + let shardRef = ref.collection("shards").document(String(shardId)) - shardRef.updateData([ - "count": FieldValue.increment(Int64(1)) - ]) - } - // [END increment_counter] + shardRef.updateData([ + "count": FieldValue.increment(Int64(1)) + ]) + } + // [END increment_counter] - // [START get_count] - func getCount(ref: DocumentReference) { - ref.collection("shards").getDocuments() { (querySnapshot, err) in - var totalCount = 0 - if err != nil { - // Error getting shards - // ... - } else { - for document in querySnapshot!.documents { - let count = document.data()["count"] as! Int - totalCount += count - } - } + // [START get_count] + func getCount(ref: DocumentReference) async { + do { + let querySnapshot = try await ref.collection("shards").getDocuments() + var totalCount = 0 + for document in querySnapshot.documents { + let count = document.data()["count"] as! Int + totalCount += count + } - print("Total count is \(totalCount)") - } + print("Total count is \(totalCount)") + } catch { + // handle error } - // [END get_count] + } + // [END get_count] } diff --git a/firestore/swift/firestore-smoketest/SolutionGeoPointViewController.swift b/firestore/swift/firestore-smoketest/SolutionGeoPointViewController.swift index fa83af64..963f3f78 100644 --- a/firestore/swift/firestore-smoketest/SolutionGeoPointViewController.swift +++ b/firestore/swift/firestore-smoketest/SolutionGeoPointViewController.swift @@ -18,88 +18,98 @@ import UIKit import FirebaseCore import FirebaseFirestore -import GeoFire +import GeoFireUtils import CoreLocation class SolutionGeoPointController: UIViewController { - var db: Firestore! + var db: Firestore! - override func viewDidLoad() { - super.viewDidLoad() - db = Firestore.firestore() - } + override func viewDidLoad() { + super.viewDidLoad() + db = Firestore.firestore() + } - func storeGeoHash() { - // [START fs_geo_add_hash] - // Compute the GeoHash for a lat/lng point - let latitude = 51.5074 - let longitude = 0.12780 - let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + func storeGeoHash() { + // [START fs_geo_add_hash] + // Compute the GeoHash for a lat/lng point + let latitude = 51.5074 + let longitude = 0.12780 + let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) - let hash = GFUtils.geoHash(forLocation: location) + let hash = GFUtils.geoHash(forLocation: location) - // Add the hash and the lat/lng to the document. We will use the hash - // for queries and the lat/lng for distance comparisons. - let documentData: [String: Any] = [ - "geohash": hash, - "lat": latitude, - "lng": longitude - ] + // Add the hash and the lat/lng to the document. We will use the hash + // for queries and the lat/lng for distance comparisons. + let documentData: [String: Any] = [ + "geohash": hash, + "lat": latitude, + "lng": longitude + ] - let londonRef = db.collection("cities").document("LON") - londonRef.updateData(documentData) { error in - // ... - } - // [END fs_geo_add_hash] + let londonRef = db.collection("cities").document("LON") + londonRef.updateData(documentData) { error in + // ... } + // [END fs_geo_add_hash] + } - func geoQuery() { - // [START fs_geo_query_hashes] - // Find cities within 50km of London - let center = CLLocationCoordinate2D(latitude: 51.5074, longitude: 0.1278) - let radiusInM: Double = 50 * 1000 - - // Each item in 'bounds' represents a startAt/endAt pair. We have to issue - // a separate query for each pair. There can be up to 9 pairs of bounds - // depending on overlap, but in most cases there are 4. - let queryBounds = GFUtils.queryBounds(forLocation: center, - withRadius: radiusInM) - let queries = queryBounds.map { bound -> Query in - return db.collection("cities") - .order(by: "geohash") - .start(at: [bound.startValue]) - .end(at: [bound.endValue]) - } + func geoQuery() async { + // [START fs_geo_query_hashes] + // Find cities within 50km of London + let center = CLLocationCoordinate2D(latitude: 51.5074, longitude: 0.1278) + let radiusInM: Double = 50 * 1000 - var matchingDocs = [QueryDocumentSnapshot]() - // Collect all the query results together into a single list - func getDocumentsCompletion(snapshot: QuerySnapshot?, error: Error?) -> () { - guard let documents = snapshot?.documents else { - print("Unable to fetch snapshot data. \(String(describing: error))") - return - } + // Each item in 'bounds' represents a startAt/endAt pair. We have to issue + // a separate query for each pair. There can be up to 9 pairs of bounds + // depending on overlap, but in most cases there are 4. + let queryBounds = GFUtils.queryBounds(forLocation: center, + withRadius: radiusInM) + let queries = queryBounds.map { bound -> Query in + return db.collection("cities") + .order(by: "geohash") + .start(at: [bound.startValue]) + .end(at: [bound.endValue]) + } - for document in documents { - let lat = document.data()["lat"] as? Double ?? 0 - let lng = document.data()["lng"] as? Double ?? 0 - let coordinates = CLLocation(latitude: lat, longitude: lng) - let centerPoint = CLLocation(latitude: center.latitude, longitude: center.longitude) + @Sendable func fetchMatchingDocs(from query: Query, + center: CLLocationCoordinate2D, + radiusInMeters: Double) async throws -> [QueryDocumentSnapshot] { + let snapshot = try await query.getDocuments() + // Collect all the query results together into a single list + return snapshot.documents.filter { document in + let lat = document.data()["lat"] as? Double ?? 0 + let lng = document.data()["lng"] as? Double ?? 0 + let coordinates = CLLocation(latitude: lat, longitude: lng) + let centerPoint = CLLocation(latitude: center.latitude, longitude: center.longitude) - // We have to filter out a few false positives due to GeoHash accuracy, but - // most will match - let distance = GFUtils.distance(from: centerPoint, to: coordinates) - if distance <= radiusInM { - matchingDocs.append(document) - } - } - } + // We have to filter out a few false positives due to GeoHash accuracy, but + // most will match + let distance = GFUtils.distance(from: centerPoint, to: coordinates) + return distance <= radiusInM + } + } - // After all callbacks have executed, matchingDocs contains the result. Note that this - // sample does not demonstrate how to wait on all callbacks to complete. + // After all callbacks have executed, matchingDocs contains the result. Note that this code + // executes all queries serially, which may not be optimal for performance. + do { + let matchingDocs = try await withThrowingTaskGroup(of: [QueryDocumentSnapshot].self) { group -> [QueryDocumentSnapshot] in for query in queries { - query.getDocuments(completion: getDocumentsCompletion) + group.addTask { + try await fetchMatchingDocs(from: query, center: center, radiusInMeters: radiusInM) + } } - // [END fs_geo_query_hashes] + var matchingDocs = [QueryDocumentSnapshot]() + for try await documents in group { + matchingDocs.append(contentsOf: documents) + } + return matchingDocs + } + + print("Docs matching geoquery: \(matchingDocs)") + } catch { + print("Unable to fetch snapshot data. \(error)") } + // [END fs_geo_query_hashes] + } } diff --git a/firestore/swift/firestore-smoketest/ViewController.swift b/firestore/swift/firestore-smoketest/ViewController.swift index d25fddbb..e92eefec 100644 --- a/firestore/swift/firestore-smoketest/ViewController.swift +++ b/firestore/swift/firestore-smoketest/ViewController.swift @@ -18,1291 +18,1448 @@ import UIKit import FirebaseCore import FirebaseFirestore -import FirebaseFirestoreSwift class ViewController: UIViewController { - var db: Firestore! - - override func viewDidLoad() { - super.viewDidLoad() - - // [START setup] - let settings = FirestoreSettings() - - Firestore.firestore().settings = settings - // [END setup] - db = Firestore.firestore() - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - } - - @IBAction func didTouchSmokeTestButton(_ sender: AnyObject) { - // Quickstart - addAdaLovelace() - addAlanTuring() - getCollection() - listenForUsers() - - // Structure Data - demonstrateReferences() - - // Save Data - setDocument() - dataTypes() - setData() - addDocument() - newDocument() - updateDocument() - createIfMissing() - updateDocumentNested() - deleteDocument() - deleteCollection() - deleteField() - serverTimestamp() - serverTimestampOptions() - simpleTransaction() - transaction() - writeBatch() - - // Retrieve Data - exampleData() - exampleDataCollectionGroup() - getDocument() - customClassGetDocument() - listenDocument() - listenDocumentLocal() - listenWithMetadata() - getMultiple() - getMultipleAll() - listenMultiple() - listenDiffs() - listenState() - detachListener() - handleListenErrors() - - // Query Data - simpleQueries() - exampleFilters() - onlyCapitals() - chainFilters() - validRangeFilters() - - // IN Queries - arrayContainsAnyQueries() - inQueries() - - // Can't run this since it throws a fatal error - // invalidRangeFilters() - - orderAndLimit() - orderAndLimitDesc() - orderMultiple() - filterAndOrder() - validFilterAndOrder() - - // Can't run this since it throws a fatal error - // invalidFilterAndOrder() - - // Enable Offline - // Can't run this since it throws a fatal error - // enableOffline() - listenToOffline() - toggleOffline() - setupCacheSize() - - // Cursors - simpleCursor() - snapshotCursor() - paginate() - multiCursor() - } + var db: Firestore! + + override func viewDidLoad() { + super.viewDidLoad() + + // [START setup] + let settings = FirestoreSettings() + + Firestore.firestore().settings = settings + // [END setup] + db = Firestore.firestore() + } + + @IBAction func didTouchSmokeTestButton(_ sender: AnyObject) { + // Quickstart + Task { + await addAdaLovelace() + await addAlanTuring() + await getCollection() + listenForUsers() + } + + // Structure Data + demonstrateReferences() + + // Save Data + Task { + await setDocument() + await dataTypes() + setData() + await addDocument() + newDocument() + await updateDocument() + createIfMissing() + await updateDocumentNested() + await deleteDocument() + deleteCollection() + await deleteField() + await serverTimestamp() + serverTimestampOptions() + await simpleTransaction() + await transaction() + await writeBatch() + } + + // Retrieve Data + Task { + exampleData() + exampleDataCollectionGroup() + await getDocument() + await customClassGetDocument() + listenDocument() + listenDocumentLocal() + listenWithMetadata() + await getMultiple() + await getMultipleAll() + listenMultiple() + listenDiffs() + listenState() + detachListener() + handleListenErrors() + } + + // Query Data + simpleQueries() + exampleFilters() + onlyCapitals() + chainFilters() + validRangeFilters() + + // IN Queries + arrayContainsAnyQueries() + inQueries() + + // Can't run this since it throws a fatal error + // invalidRangeFilters() + + orderAndLimit() + orderAndLimitDesc() + orderMultiple() + filterAndOrder() + validFilterAndOrder() + + // Can't run this since it throws a fatal error + // invalidFilterAndOrder() + + // Enable Offline + // Can't run this since it throws a fatal error + // enableOffline() + listenToOffline() + toggleOffline() + setupCacheSize() + + // Cursors + simpleCursor() + snapshotCursor() + paginate() + multiCursor() + } + + @IBAction func didTouchDeleteButton(_ sender: AnyObject) { + deleteCollection(collection: "users") + deleteCollection(collection: "cities") + } + + private func deleteCollection(collection: String) { + db.collection(collection).getDocuments() { (querySnapshot, err) in + if let err = err { + print("Error getting documents: \(err)") + return + } - @IBAction func didTouchDeleteButton(_ sender: AnyObject) { - deleteCollection(collection: "users") - deleteCollection(collection: "cities") + for document in querySnapshot!.documents { + print("Deleting \(document.documentID) => \(document.data())") + document.reference.delete() + } } - - private func deleteCollection(collection: String) { - db.collection(collection).getDocuments() { (querySnapshot, err) in - if let err = err { - print("Error getting documents: \(err)") - return - } - - for document in querySnapshot!.documents { - print("Deleting \(document.documentID) => \(document.data())") - document.reference.delete() - } + } + + private func setupCacheSize() { + // [START fs_setup_cache] + let settings = Firestore.firestore().settings + // Set cache size to 100 MB + settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber) + Firestore.firestore().settings = settings + // [END fs_setup_cache] + } + + // ======================================================================================= + // ======== https://firebase.google.com/preview/firestore/client/quickstart ============== + // ======================================================================================= + + private func addAdaLovelace() async { + // [START add_ada_lovelace] + // Add a new document with a generated ID + do { + let ref = try await db.collection("users").addDocument(data: [ + "first": "Ada", + "last": "Lovelace", + "born": 1815 + ]) + print("Document added with ID: \(ref.documentID)") + } catch { + print("Error adding document: \(error)") + } + // [END add_ada_lovelace] + } + + private func addAlanTuring() async { + // [START add_alan_turing] + // Add a second document with a generated ID. + do { + let ref = try await db.collection("users").addDocument(data: [ + "first": "Alan", + "middle": "Mathison", + "last": "Turing", + "born": 1912 + ]) + print("Document added with ID: \(ref.documentID)") + } catch { + print("Error adding document: \(error)") + } + // [END add_alan_turing] + } + + private func getCollection() async { + // [START get_collection] + do { + let snapshot = try await db.collection("users").getDocuments() + for document in snapshot.documents { + print("\(document.documentID) => \(document.data())") + } + } catch { + print("Error getting documents: \(error)") + } + // [END get_collection] + } + + private func listenForUsers() { + // [START listen_for_users] + // Listen to a query on a collection. + // + // We will get a first snapshot with the initial results and a new + // snapshot each time there is a change in the results. + db.collection("users") + .whereField("born", isLessThan: 1900) + .addSnapshotListener { querySnapshot, error in + guard let snapshot = querySnapshot else { + print("Error retreiving snapshots \(error!)") + return } - } - - private func setupCacheSize() { - // [START fs_setup_cache] - let settings = Firestore.firestore().settings - settings.cacheSizeBytes = FirestoreCacheSizeUnlimited - Firestore.firestore().settings = settings - // [END fs_setup_cache] - } - - // ======================================================================================= - // ======== https://firebase.google.com/preview/firestore/client/quickstart ============== - // ======================================================================================= - - private func addAdaLovelace() { - // [START add_ada_lovelace] - // Add a new document with a generated ID - var ref: DocumentReference? = nil - ref = db.collection("users").addDocument(data: [ - "first": "Ada", - "last": "Lovelace", - "born": 1815 - ]) { err in - if let err = err { - print("Error adding document: \(err)") - } else { - print("Document added with ID: \(ref!.documentID)") - } + print("Current users born before 1900: \(snapshot.documents.map { $0.data() })") + } + // [END listen_for_users] + } + + // ======================================================================================= + // ======= https://firebase.google.com/preview/firestore/client/structure-data =========== + // ======================================================================================= + + + private func demonstrateReferences() { + // [START doc_reference] + let alovelaceDocumentRef = db.collection("users").document("alovelace") + // [END doc_reference] + print(alovelaceDocumentRef) + + // [START collection_reference] + let usersCollectionRef = db.collection("users") + // [END collection_reference] + print(usersCollectionRef) + + // [START subcollection_reference] + let messageRef = db + .collection("rooms").document("roomA") + .collection("messages").document("message1") + // [END subcollection_reference] + print(messageRef) + + // [START path_reference] + let aLovelaceDocumentReference = db.document("users/alovelace") + // [END path_reference] + print(aLovelaceDocumentReference) + } + + // ======================================================================================= + // ========= https://firebase.google.com/preview/firestore/client/save-data ============== + // ======================================================================================= + + private func setDocument() async { + // [START set_document] + // Add a new document in collection "cities" + do { + try await db.collection("cities").document("LA").setData([ + "name": "Los Angeles", + "state": "CA", + "country": "USA" + ]) + print("Document successfully written!") + } catch { + print("Error writing document: \(error)") + } + // [END set_document] + } + + private func setDocumentWithCodable() { + // [START set_document_codable] + let city = City(name: "Los Angeles", + state: "CA", + country: "USA", + isCapital: false, + population: 5000000) + + do { + try db.collection("cities").document("LA").setData(from: city) + } catch let error { + print("Error writing city to Firestore: \(error)") + } + // [END set_document_codable] + } + + private func dataTypes() async { + // [START data_types] + let docData: [String: Any] = [ + "stringExample": "Hello world!", + "booleanExample": true, + "numberExample": 3.14159265, + "dateExample": Timestamp(date: Date()), + "arrayExample": [5, true, "hello"], + "nullExample": NSNull(), + "objectExample": [ + "a": 5, + "b": [ + "nested": "foo" + ] + ] + ] + do { + try await db.collection("data").document("one").setData(docData) + print("Document successfully written!") + } catch { + print("Error writing document: \(error)") + } + // [END data_types] + } + + private func setData() { + let data: [String: Any] = [:] + + // [START set_data] + db.collection("cities").document("new-city-id").setData(data) + // [END set_data] + } + + private func addDocument() async { + // [START add_document] + // Add a new document with a generated id. + do { + let ref = try await db.collection("cities").addDocument(data: [ + "name": "Tokyo", + "country": "Japan" + ]) + print("Document added with ID: \(ref.documentID)") + } catch { + print("Error adding document: \(error)") + } + // [END add_document] + } + + private func newDocument() { + // [START new_document] + let newCityRef = db.collection("cities").document() + + // later... + newCityRef.setData([ + // [START_EXCLUDE] + "name": "Some City Name" + // [END_EXCLUDE] + ]) + // [END new_document] + } + + private func updateDocument() async { + // [START update_document] + let washingtonRef = db.collection("cities").document("DC") + + // Set the "capital" field of the city 'DC' + do { + try await washingtonRef.updateData([ + "capital": true + ]) + print("Document successfully updated") + } catch { + print("Error updating document: \(error)") + } + // [END update_document] + } + + private func updateDocumentArray() { + // [START update_document_array] + let washingtonRef = db.collection("cities").document("DC") + + // Atomically add a new region to the "regions" array field. + washingtonRef.updateData([ + "regions": FieldValue.arrayUnion(["greater_virginia"]) + ]) + + // Atomically remove a region from the "regions" array field. + washingtonRef.updateData([ + "regions": FieldValue.arrayRemove(["east_coast"]) + ]) + // [END update_document_array] + } + + private func updateDocumentIncrement() { + // [START update_document-increment] + let washingtonRef = db.collection("cities").document("DC") + + // Atomically increment the population of the city by 50. + // Note that increment() with no arguments increments by 1. + washingtonRef.updateData([ + "population": FieldValue.increment(Int64(50)) + ]) + // [END update_document-increment] + } + + private func createIfMissing() { + // [START create_if_missing] + // Update one field, creating the document if it does not exist. + db.collection("cities").document("BJ").setData([ "capital": true ], merge: true) + // [END create_if_missing] + } + + private func updateDocumentNested() async { + // [START update_document_nested] + // Create an initial document to update. + let frankDocRef = db.collection("users").document("frank") + do { + try await frankDocRef.setData([ + "name": "Frank", + "favorites": [ "food": "Pizza", "color": "Blue", "subject": "recess" ], + "age": 12 + ]) + + // To update age and favorite color: + try await frankDocRef.updateData([ + "age": 13, + "favorites.color": "Red" + ]) + print("Document successfully updated") + } catch { + print("Error updating document: \(error)") + } + // [END update_document_nested] + } + + private func deleteDocument() async { + // [START delete_document] + do { + try await db.collection("cities").document("DC").delete() + print("Document successfully removed!") + } catch { + print("Error removing document: \(error)") + } + // [END delete_document] + } + + private func deleteCollection() { + // [START delete_collection] + func delete(collection: CollectionReference, batchSize: Int = 100, completion: @escaping (Error?) -> ()) { + // Limit query to avoid out-of-memory errors on large collections. + // When deleting a collection guaranteed to fit in memory, batching can be avoided entirely. + collection.limit(to: batchSize).getDocuments { (docset, error) in + // An error occurred. + guard let docset = docset else { + completion(error) + return } - // [END add_ada_lovelace] - } - - private func addAlanTuring() { - var ref: DocumentReference? = nil - - // [START add_alan_turing] - // Add a second document with a generated ID. - ref = db.collection("users").addDocument(data: [ - "first": "Alan", - "middle": "Mathison", - "last": "Turing", - "born": 1912 - ]) { err in - if let err = err { - print("Error adding document: \(err)") - } else { - print("Document added with ID: \(ref!.documentID)") - } + // There's nothing to delete. + guard docset.count > 0 else { + completion(nil) + return } - // [END add_alan_turing] - } - private func getCollection() { - // [START get_collection] - db.collection("users").getDocuments() { (querySnapshot, err) in - if let err = err { - print("Error getting documents: \(err)") - } else { - for document in querySnapshot!.documents { - print("\(document.documentID) => \(document.data())") - } - } + let batch = collection.firestore.batch() + docset.documents.forEach { batch.deleteDocument($0.reference) } + + batch.commit { (batchError) in + if let batchError = batchError { + // Stop the deletion process and handle the error. Some elements + // may have been deleted. + completion(batchError) + } else { + delete(collection: collection, batchSize: batchSize, completion: completion) + } } - // [END get_collection] - } - - private func listenForUsers() { - // [START listen_for_users] - // Listen to a query on a collection. - // - // We will get a first snapshot with the initial results and a new - // snapshot each time there is a change in the results. - db.collection("users") - .whereField("born", isLessThan: 1900) - .addSnapshotListener { querySnapshot, error in - guard let snapshot = querySnapshot else { - print("Error retreiving snapshots \(error!)") - return - } - print("Current users born before 1900: \(snapshot.documents.map { $0.data() })") - } - // [END listen_for_users] - } - - // ======================================================================================= - // ======= https://firebase.google.com/preview/firestore/client/structure-data =========== - // ======================================================================================= - - - private func demonstrateReferences() { - // [START doc_reference] - let alovelaceDocumentRef = db.collection("users").document("alovelace") - // [END doc_reference] - print(alovelaceDocumentRef) - - // [START collection_reference] - let usersCollectionRef = db.collection("users") - // [END collection_reference] - print(usersCollectionRef) - - // [START subcollection_reference] - let messageRef = db - .collection("rooms").document("roomA") - .collection("messages").document("message1") - // [END subcollection_reference] - print(messageRef) - - // [START path_reference] - let aLovelaceDocumentReference = db.document("users/alovelace") - // [END path_reference] - print(aLovelaceDocumentReference) - } - - // ======================================================================================= - // ========= https://firebase.google.com/preview/firestore/client/save-data ============== - // ======================================================================================= - - private func setDocument() { - // [START set_document] - // Add a new document in collection "cities" - db.collection("cities").document("LA").setData([ - "name": "Los Angeles", - "state": "CA", - "country": "USA" - ]) { err in - if let err = err { - print("Error writing document: \(err)") - } else { - print("Document successfully written!") - } - } - // [END set_document] + } } - - private func setDocumentWithCodable() { - // [START set_document_codable] - let city = City(name: "Los Angeles", - state: "CA", - country: "USA", - isCapital: false, - population: 5000000) - + // [END delete_collection] + } + + private func deleteField() async { + // [START delete_field] + do { + + try await db.collection("cities").document("BJ").updateData([ + "capital": FieldValue.delete(), + ]) + print("Document successfully updated") + } catch { + print("Error updating document: \(error)") + } + // [END delete_field] + } + + private func serverTimestamp() async { + // [START server_timestamp] + do { + try await db.collection("objects").document("some-id").updateData([ + "lastUpdated": FieldValue.serverTimestamp(), + ]) + print("Document successfully updated") + } catch { + print("Error updating document: \(error)") + } + // [END server_timestamp] + } + + private func serverTimestampOptions() { + // [START server_timestamp_options] + // Perform an update followed by an immediate read without waiting for the update to + // complete. Due to the snapshot options we will get two results: one with an estimated + // timestamp and one with a resolved server timestamp. + let docRef = db.collection("objects").document("some-id") + docRef.updateData(["timestamp": FieldValue.serverTimestamp()]) + + docRef.addSnapshotListener { (snapshot, error) in + guard let timestamp = snapshot?.data(with: .estimate)?["timestamp"] else { return } + guard let pendingWrites = snapshot?.metadata.hasPendingWrites else { return } + print("Timestamp: \(timestamp), pending: \(pendingWrites)") + } + // [END server_timestamp_options] + } + + private func simpleTransaction() async { + // [START simple_transaction] + let sfReference = db.collection("cities").document("SF") + + do { + let _ = try await db.runTransaction({ (transaction, errorPointer) -> Any? in + let sfDocument: DocumentSnapshot do { - try db.collection("cities").document("LA").setData(from: city) - } catch let error { - print("Error writing city to Firestore: \(error)") + try sfDocument = transaction.getDocument(sfReference) + } catch let fetchError as NSError { + errorPointer?.pointee = fetchError + return nil } - // [END set_document_codable] - } - private func dataTypes() { - // [START data_types] - let docData: [String: Any] = [ - "stringExample": "Hello world!", - "booleanExample": true, - "numberExample": 3.14159265, - "dateExample": Timestamp(date: Date()), - "arrayExample": [5, true, "hello"], - "nullExample": NSNull(), - "objectExample": [ - "a": 5, - "b": [ - "nested": "foo" - ] + guard let oldPopulation = sfDocument.data()?["population"] as? Int else { + let error = NSError( + domain: "AppErrorDomain", + code: -1, + userInfo: [ + NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" ] - ] - db.collection("data").document("one").setData(docData) { err in - if let err = err { - print("Error writing document: \(err)") - } else { - print("Document successfully written!") - } - } - // [END data_types] - } - - private func setData() { - let data: [String: Any] = [:] - - // [START set_data] - db.collection("cities").document("new-city-id").setData(data) - // [END set_data] - } - - private func addDocument() { - // [START add_document] - // Add a new document with a generated id. - var ref: DocumentReference? = nil - ref = db.collection("cities").addDocument(data: [ - "name": "Tokyo", - "country": "Japan" - ]) { err in - if let err = err { - print("Error adding document: \(err)") - } else { - print("Document added with ID: \(ref!.documentID)") - } + ) + errorPointer?.pointee = error + return nil } - // [END add_document] - } - - private func newDocument() { - // [START new_document] - let newCityRef = db.collection("cities").document() - - // later... - newCityRef.setData([ - // [START_EXCLUDE] - "name": "Some City Name" - // [END_EXCLUDE] - ]) - // [END new_document] - } - - private func updateDocument() { - // [START update_document] - let washingtonRef = db.collection("cities").document("DC") - - // Set the "capital" field of the city 'DC' - washingtonRef.updateData([ - "capital": true - ]) { err in - if let err = err { - print("Error updating document: \(err)") - } else { - print("Document successfully updated") - } - } - // [END update_document] - } - - private func updateDocumentArray() { - // [START update_document_array] - let washingtonRef = db.collection("cities").document("DC") - - // Atomically add a new region to the "regions" array field. - washingtonRef.updateData([ - "regions": FieldValue.arrayUnion(["greater_virginia"]) - ]) - - // Atomically remove a region from the "regions" array field. - washingtonRef.updateData([ - "regions": FieldValue.arrayRemove(["east_coast"]) - ]) - // [END update_document_array] - } - - private func updateDocumentIncrement() { - // [START update_document-increment] - let washingtonRef = db.collection("cities").document("DC") - - // Atomically increment the population of the city by 50. - // Note that increment() with no arguments increments by 1. - washingtonRef.updateData([ - "population": FieldValue.increment(Int64(50)) - ]) - // [END update_document-increment] - } - - private func createIfMissing() { - // [START create_if_missing] - // Update one field, creating the document if it does not exist. - db.collection("cities").document("BJ").setData([ "capital": true ], merge: true) - // [END create_if_missing] - } - private func updateDocumentNested() { - // [START update_document_nested] - // Create an initial document to update. - let frankDocRef = db.collection("users").document("frank") - frankDocRef.setData([ - "name": "Frank", - "favorites": [ "food": "Pizza", "color": "Blue", "subject": "recess" ], - "age": 12 - ]) - - // To update age and favorite color: - db.collection("users").document("frank").updateData([ - "age": 13, - "favorites.color": "Red" - ]) { err in - if let err = err { - print("Error updating document: \(err)") - } else { - print("Document successfully updated") - } + // Note: this could be done without a transaction + // by updating the population using FieldValue.increment() + transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference) + return nil + }) + print("Transaction successfully committed!") + } catch { + print("Transaction failed: \(error)") + } + // [END simple_transaction] + } + + private func transaction() async { + // [START transaction] + let sfReference = db.collection("cities").document("SF") + + do { + let object = try await db.runTransaction({ (transaction, errorPointer) -> Any? in + let sfDocument: DocumentSnapshot + do { + try sfDocument = transaction.getDocument(sfReference) + } catch let fetchError as NSError { + errorPointer?.pointee = fetchError + return nil } - // [END update_document_nested] - } - private func deleteDocument() { - // [START delete_document] - db.collection("cities").document("DC").delete() { err in - if let err = err { - print("Error removing document: \(err)") - } else { - print("Document successfully removed!") - } + guard let oldPopulation = sfDocument.data()?["population"] as? Int else { + let error = NSError( + domain: "AppErrorDomain", + code: -1, + userInfo: [ + NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" + ] + ) + errorPointer?.pointee = error + return nil } - // [END delete_document] - } - private func deleteCollection() { - // [START delete_collection] - func delete(collection: CollectionReference, batchSize: Int = 100, completion: @escaping (Error?) -> ()) { - // Limit query to avoid out-of-memory errors on large collections. - // When deleting a collection guaranteed to fit in memory, batching can be avoided entirely. - collection.limit(to: batchSize).getDocuments { (docset, error) in - // An error occurred. - guard let docset = docset else { - completion(error) - return - } - // There's nothing to delete. - guard docset.count > 0 else { - completion(nil) - return - } - - let batch = collection.firestore.batch() - docset.documents.forEach { batch.deleteDocument($0.reference) } - - batch.commit { (batchError) in - if let batchError = batchError { - // Stop the deletion process and handle the error. Some elements - // may have been deleted. - completion(batchError) - } else { - delete(collection: collection, batchSize: batchSize, completion: completion) - } - } - } + // Note: this could be done without a transaction + // by updating the population using FieldValue.increment() + let newPopulation = oldPopulation + 1 + guard newPopulation <= 1000000 else { + let error = NSError( + domain: "AppErrorDomain", + code: -2, + userInfo: [NSLocalizedDescriptionKey: "Population \(newPopulation) too big"] + ) + errorPointer?.pointee = error + return nil } - // [END delete_collection] - } - private func deleteField() { - // [START delete_field] - db.collection("cities").document("BJ").updateData([ - "capital": FieldValue.delete(), - ]) { err in - if let err = err { - print("Error updating document: \(err)") - } else { - print("Document successfully updated") - } - } - // [END delete_field] + transaction.updateData(["population": newPopulation], forDocument: sfReference) + return newPopulation + }) + print("Population increased to \(object!)") + } catch { + print("Error updating population: \(error)") + } + // [END transaction] + } + + private func writeBatch() async { + // [START write_batch] + // Get new write batch + let batch = db.batch() + + // Set the value of 'NYC' + let nycRef = db.collection("cities").document("NYC") + batch.setData([:], forDocument: nycRef) + + // Update the population of 'SF' + let sfRef = db.collection("cities").document("SF") + batch.updateData(["population": 1000000 ], forDocument: sfRef) + + // Delete the city 'LA' + let laRef = db.collection("cities").document("LA") + batch.deleteDocument(laRef) + + // Commit the batch + do { + try await batch.commit() + print("Batch write succeeded.") + } catch { + print("Error writing batch: \(error)") + } + // [END write_batch] + } + + // ======================================================================================= + // ======= https://firebase.google.com/preview/firestore/client/retrieve-data ============ + // ======================================================================================= + + private func exampleData() { + // [START example_data] + let citiesRef = db.collection("cities") + + citiesRef.document("SF").setData([ + "name": "San Francisco", + "state": "CA", + "country": "USA", + "capital": false, + "population": 860000, + "regions": ["west_coast", "norcal"] + ]) + citiesRef.document("LA").setData([ + "name": "Los Angeles", + "state": "CA", + "country": "USA", + "capital": false, + "population": 3900000, + "regions": ["west_coast", "socal"] + ]) + citiesRef.document("DC").setData([ + "name": "Washington D.C.", + "country": "USA", + "capital": true, + "population": 680000, + "regions": ["east_coast"] + ]) + citiesRef.document("TOK").setData([ + "name": "Tokyo", + "country": "Japan", + "capital": true, + "population": 9000000, + "regions": ["kanto", "honshu"] + ]) + citiesRef.document("BJ").setData([ + "name": "Beijing", + "country": "China", + "capital": true, + "population": 21500000, + "regions": ["jingjinji", "hebei"] + ]) + // [END example_data] + } + + private func exampleDataCollectionGroup() { + // [START fs_collection_group_query_data_setup] + let citiesRef = db.collection("cities") + + var data = ["name": "Golden Gate Bridge", "type": "bridge"] + citiesRef.document("SF").collection("landmarks").addDocument(data: data) + + data = ["name": "Legion of Honor", "type": "museum"] + citiesRef.document("SF").collection("landmarks").addDocument(data: data) + + data = ["name": "Griffith Park", "type": "park"] + citiesRef.document("LA").collection("landmarks").addDocument(data: data) + + data = ["name": "The Getty", "type": "museum"] + citiesRef.document("LA").collection("landmarks").addDocument(data: data) + + data = ["name": "Lincoln Memorial", "type": "memorial"] + citiesRef.document("DC").collection("landmarks").addDocument(data: data) + + data = ["name": "National Air and Space Museum", "type": "museum"] + citiesRef.document("DC").collection("landmarks").addDocument(data: data) + + data = ["name": "Ueno Park", "type": "park"] + citiesRef.document("TOK").collection("landmarks").addDocument(data: data) + + data = ["name": "National Museum of Nature and Science", "type": "museum"] + citiesRef.document("TOK").collection("landmarks").addDocument(data: data) + + data = ["name": "Jingshan Park", "type": "park"] + citiesRef.document("BJ").collection("landmarks").addDocument(data: data) + + data = ["name": "Beijing Ancient Observatory", "type": "museum"] + citiesRef.document("BJ").collection("landmarks").addDocument(data: data) + // [END fs_collection_group_query_data_setup] + } + + private func getDocument() async { + // [START get_document] + let docRef = db.collection("cities").document("SF") + + do { + let document = try await docRef.getDocument() + if document.exists { + let dataDescription = document.data().map(String.init(describing:)) ?? "nil" + print("Document data: \(dataDescription)") + } else { + print("Document does not exist") + } + } catch { + print("Error getting document: \(error)") } + // [END get_document] + } - private func serverTimestamp() { - // [START server_timestamp] - db.collection("objects").document("some-id").updateData([ - "lastUpdated": FieldValue.serverTimestamp(), - ]) { err in - if let err = err { - print("Error updating document: \(err)") - } else { - print("Document successfully updated") - } - } - // [END server_timestamp] - } + private func getDocumentWithOptions() async { + // [START get_document_options] + let docRef = db.collection("cities").document("SF") - private func serverTimestampOptions() { - // [START server_timestamp_options] - // Perform an update followed by an immediate read without waiting for the update to - // complete. Due to the snapshot options we will get two results: one with an estimated - // timestamp and one with a resolved server timestamp. - let docRef = db.collection("objects").document("some-id") - docRef.updateData(["timestamp": FieldValue.serverTimestamp()]) - - docRef.addSnapshotListener { (snapshot, error) in - guard let timestamp = snapshot?.data(with: .estimate)?["timestamp"] else { return } - guard let pendingWrites = snapshot?.metadata.hasPendingWrites else { return } - print("Timestamp: \(timestamp), pending: \(pendingWrites)") + do { + // Force the SDK to fetch the document from the cache. Could also specify + // FirestoreSource.server or FirestoreSource.default. + let document = try await docRef.getDocument(source: .cache) + if document.exists { + let dataDescription = document.data().map(String.init(describing:)) ?? "nil" + print("Cached document data: \(dataDescription)") + } else { + print("Document does not exist in cache") + } + } catch { + print("Error getting document: \(error)") + } + // [END get_document_options] + } + + private func customClassGetDocument() async { + // [START custom_type] + let docRef = db.collection("cities").document("BJ") + + do { + let city = try await docRef.getDocument(as: City.self) + print("City: \(city)") + } catch { + print("Error decoding city: \(error)") + } + // [END custom_type] + } + + private func listenDocument() { + // [START listen_document] + db.collection("cities").document("SF") + .addSnapshotListener { documentSnapshot, error in + guard let document = documentSnapshot else { + print("Error fetching document: \(error!)") + return } - // [END server_timestamp_options] - } - - private func simpleTransaction() { - // [START simple_transaction] - let sfReference = db.collection("cities").document("SF") - - db.runTransaction({ (transaction, errorPointer) -> Any? in - let sfDocument: DocumentSnapshot - do { - try sfDocument = transaction.getDocument(sfReference) - } catch let fetchError as NSError { - errorPointer?.pointee = fetchError - return nil - } - - guard let oldPopulation = sfDocument.data()?["population"] as? Int else { - let error = NSError( - domain: "AppErrorDomain", - code: -1, - userInfo: [ - NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" - ] - ) - errorPointer?.pointee = error - return nil - } - - // Note: this could be done without a transaction - // by updating the population using FieldValue.increment() - transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference) - return nil - }) { (object, error) in - if let error = error { - print("Transaction failed: \(error)") - } else { - print("Transaction successfully committed!") - } + guard let data = document.data() else { + print("Document data was empty.") + return } - // [END simple_transaction] - } - - private func transaction() { - // [START transaction] - let sfReference = db.collection("cities").document("SF") - - db.runTransaction({ (transaction, errorPointer) -> Any? in - let sfDocument: DocumentSnapshot - do { - try sfDocument = transaction.getDocument(sfReference) - } catch let fetchError as NSError { - errorPointer?.pointee = fetchError - return nil - } - - guard let oldPopulation = sfDocument.data()?["population"] as? Int else { - let error = NSError( - domain: "AppErrorDomain", - code: -1, - userInfo: [ - NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" - ] - ) - errorPointer?.pointee = error - return nil - } - - // Note: this could be done without a transaction - // by updating the population using FieldValue.increment() - let newPopulation = oldPopulation + 1 - guard newPopulation <= 1000000 else { - let error = NSError( - domain: "AppErrorDomain", - code: -2, - userInfo: [NSLocalizedDescriptionKey: "Population \(newPopulation) too big"] - ) - errorPointer?.pointee = error - return nil - } - - transaction.updateData(["population": newPopulation], forDocument: sfReference) - return newPopulation - }) { (object, error) in - if let error = error { - print("Error updating population: \(error)") - } else { - print("Population increased to \(object!)") - } + print("Current data: \(data)") + } + // [END listen_document] + } + + private func listenDocumentLocal() { + // [START listen_document_local] + db.collection("cities").document("SF") + .addSnapshotListener { documentSnapshot, error in + guard let document = documentSnapshot else { + print("Error fetching document: \(error!)") + return } - // [END transaction] - } - - private func writeBatch() { - // [START write_batch] - // Get new write batch - let batch = db.batch() - - // Set the value of 'NYC' - let nycRef = db.collection("cities").document("NYC") - batch.setData([:], forDocument: nycRef) - - // Update the population of 'SF' - let sfRef = db.collection("cities").document("SF") - batch.updateData(["population": 1000000 ], forDocument: sfRef) - - // Delete the city 'LA' - let laRef = db.collection("cities").document("LA") - batch.deleteDocument(laRef) - - // Commit the batch - batch.commit() { err in - if let err = err { - print("Error writing batch \(err)") - } else { - print("Batch write succeeded.") - } + let source = document.metadata.hasPendingWrites ? "Local" : "Server" + print("\(source) data: \(document.data() ?? [:])") + } + // [END listen_document_local] + } + + private func listenWithMetadata() { + // [START listen_with_metadata] + // Listen to document metadata. + db.collection("cities").document("SF") + .addSnapshotListener(includeMetadataChanges: true) { documentSnapshot, error in + // ... + } + // [END listen_with_metadata] + } + + private func getMultiple() async { + // [START get_multiple] + do { + let querySnapshot = try await db.collection("cities").whereField("capital", isEqualTo: true) + .getDocuments() + for document in querySnapshot.documents { + print("\(document.documentID) => \(document.data())") + } + } catch { + print("Error getting documents: \(error)") + } + // [END get_multiple] + } + + private func getMultipleAll() async { + // [START get_multiple_all] + do { + let querySnapshot = try await db.collection("cities").getDocuments() + for document in querySnapshot.documents { + print("\(document.documentID) => \(document.data())") + } + } catch { + print("Error getting documents: \(error)") + } + // [END get_multiple_all] + } + + private func getMultipleAllSubcollection() async { + // [START get_multiple_all_subcollection] + do { + let querySnapshot = try await db.collection("cities/SF/landmarks").getDocuments() + for document in querySnapshot.documents { + print("\(document.documentID) => \(document.data())") + } + } catch { + print("Error getting documents: \(error)") + } + // [END get_multiple_all_subcollection] + } + + private func listenMultiple() { + // [START listen_multiple] + db.collection("cities").whereField("state", isEqualTo: "CA") + .addSnapshotListener { querySnapshot, error in + guard let documents = querySnapshot?.documents else { + print("Error fetching documents: \(error!)") + return } - // [END write_batch] - } - - // ======================================================================================= - // ======= https://firebase.google.com/preview/firestore/client/retrieve-data ============ - // ======================================================================================= - - private func exampleData() { - // [START example_data] - let citiesRef = db.collection("cities") - - citiesRef.document("SF").setData([ - "name": "San Francisco", - "state": "CA", - "country": "USA", - "capital": false, - "population": 860000, - "regions": ["west_coast", "norcal"] - ]) - citiesRef.document("LA").setData([ - "name": "Los Angeles", - "state": "CA", - "country": "USA", - "capital": false, - "population": 3900000, - "regions": ["west_coast", "socal"] - ]) - citiesRef.document("DC").setData([ - "name": "Washington D.C.", - "country": "USA", - "capital": true, - "population": 680000, - "regions": ["east_coast"] - ]) - citiesRef.document("TOK").setData([ - "name": "Tokyo", - "country": "Japan", - "capital": true, - "population": 9000000, - "regions": ["kanto", "honshu"] - ]) - citiesRef.document("BJ").setData([ - "name": "Beijing", - "country": "China", - "capital": true, - "population": 21500000, - "regions": ["jingjinji", "hebei"] - ]) - // [END example_data] - } - - private func exampleDataCollectionGroup() { - // [START fs_collection_group_query_data_setup] - let citiesRef = db.collection("cities") - - var data = ["name": "Golden Gate Bridge", "type": "bridge"] - citiesRef.document("SF").collection("landmarks").addDocument(data: data) - - data = ["name": "Legion of Honor", "type": "museum"] - citiesRef.document("SF").collection("landmarks").addDocument(data: data) - - data = ["name": "Griffith Park", "type": "park"] - citiesRef.document("LA").collection("landmarks").addDocument(data: data) - - data = ["name": "The Getty", "type": "museum"] - citiesRef.document("LA").collection("landmarks").addDocument(data: data) - - data = ["name": "Lincoln Memorial", "type": "memorial"] - citiesRef.document("DC").collection("landmarks").addDocument(data: data) - - data = ["name": "National Air and Space Museum", "type": "museum"] - citiesRef.document("DC").collection("landmarks").addDocument(data: data) - - data = ["name": "Ueno Park", "type": "park"] - citiesRef.document("TOK").collection("landmarks").addDocument(data: data) - - data = ["name": "National Museum of Nature and Science", "type": "museum"] - citiesRef.document("TOK").collection("landmarks").addDocument(data: data) - - data = ["name": "Jingshan Park", "type": "park"] - citiesRef.document("BJ").collection("landmarks").addDocument(data: data) - - data = ["name": "Beijing Ancient Observatory", "type": "museum"] - citiesRef.document("BJ").collection("landmarks").addDocument(data: data) - // [END fs_collection_group_query_data_setup] - } - - private func getDocument() { - // [START get_document] - let docRef = db.collection("cities").document("SF") - - docRef.getDocument { (document, error) in - if let document = document, document.exists { - let dataDescription = document.data().map(String.init(describing:)) ?? "nil" - print("Document data: \(dataDescription)") - } else { - print("Document does not exist") - } + let cities = documents.compactMap { $0["name"] } + print("Current cities in CA: \(cities)") + } + // [END listen_multiple] + } + + private func listenDiffs() { + // [START listen_diffs] + db.collection("cities").whereField("state", isEqualTo: "CA") + .addSnapshotListener { querySnapshot, error in + guard let snapshot = querySnapshot else { + print("Error fetching snapshots: \(error!)") + return } - // [END get_document] - } - - private func getDocumentWithOptions() { - // [START get_document_options] - let docRef = db.collection("cities").document("SF") - - // Force the SDK to fetch the document from the cache. Could also specify - // FirestoreSource.server or FirestoreSource.default. - docRef.getDocument(source: .cache) { (document, error) in - if let document = document { - let dataDescription = document.data().map(String.init(describing:)) ?? "nil" - print("Cached document data: \(dataDescription)") - } else { - print("Document does not exist in cache") + snapshot.documentChanges.forEach { diff in + if (diff.type == .added) { + print("New city: \(diff.document.data())") + } + if (diff.type == .modified) { + print("Modified city: \(diff.document.data())") + } + if (diff.type == .removed) { + print("Removed city: \(diff.document.data())") + } } } - // [END get_document_options] - } - - private func customClassGetDocument() { - // [START custom_type] - let docRef = db.collection("cities").document("BJ") - - docRef.getDocument(as: City.self) { result in - // The Result type encapsulates deserialization errors or - // successful deserialization, and can be handled as follows: - // - // Result - // /\ - // Error City - switch result { - case .success(let city): - // A `City` value was successfully initialized from the DocumentSnapshot. - print("City: \(city)") - case .failure(let error): - // A `City` value could not be initialized from the DocumentSnapshot. - print("Error decoding city: \(error)") - } + // [END listen_diffs] + } + + private func listenState() { + // [START listen_state] + db.collection("cities").whereField("state", isEqualTo: "CA") + .addSnapshotListener { querySnapshot, error in + guard let snapshot = querySnapshot else { + print("Error fetching documents: \(error!)") + return } - // [END custom_type] - } - - private func listenDocument() { - // [START listen_document] - db.collection("cities").document("SF") - .addSnapshotListener { documentSnapshot, error in - guard let document = documentSnapshot else { - print("Error fetching document: \(error!)") - return - } - guard let data = document.data() else { - print("Document data was empty.") - return - } - print("Current data: \(data)") - } - // [END listen_document] - } - - private func listenDocumentLocal() { - // [START listen_document_local] - db.collection("cities").document("SF") - .addSnapshotListener { documentSnapshot, error in - guard let document = documentSnapshot else { - print("Error fetching document: \(error!)") - return - } - let source = document.metadata.hasPendingWrites ? "Local" : "Server" - print("\(source) data: \(document.data() ?? [:])") - } - // [END listen_document_local] - } - - private func listenWithMetadata() { - // [START listen_with_metadata] - // Listen to document metadata. - db.collection("cities").document("SF") - .addSnapshotListener(includeMetadataChanges: true) { documentSnapshot, error in - // ... - } - // [END listen_with_metadata] - } - - private func getMultiple() { - // [START get_multiple] - db.collection("cities").whereField("capital", isEqualTo: true) - .getDocuments() { (querySnapshot, err) in - if let err = err { - print("Error getting documents: \(err)") - } else { - for document in querySnapshot!.documents { - print("\(document.documentID) => \(document.data())") - } - } - } - // [END get_multiple] - } - - private func getMultipleAll() { - // [START get_multiple_all] - db.collection("cities").getDocuments() { (querySnapshot, err) in - if let err = err { - print("Error getting documents: \(err)") - } else { - for document in querySnapshot!.documents { - print("\(document.documentID) => \(document.data())") - } - } + snapshot.documentChanges.forEach { diff in + if (diff.type == .added) { + print("New city: \(diff.document.data())") + } } - // [END get_multiple_all] - } - private func listenMultiple() { - // [START listen_multiple] - db.collection("cities").whereField("state", isEqualTo: "CA") - .addSnapshotListener { querySnapshot, error in - guard let documents = querySnapshot?.documents else { - print("Error fetching documents: \(error!)") - return - } - let cities = documents.map { $0["name"]! } - print("Current cities in CA: \(cities)") - } - // [END listen_multiple] - } - - private func listenDiffs() { - // [START listen_diffs] - db.collection("cities").whereField("state", isEqualTo: "CA") - .addSnapshotListener { querySnapshot, error in - guard let snapshot = querySnapshot else { - print("Error fetching snapshots: \(error!)") - return - } - snapshot.documentChanges.forEach { diff in - if (diff.type == .added) { - print("New city: \(diff.document.data())") - } - if (diff.type == .modified) { - print("Modified city: \(diff.document.data())") - } - if (diff.type == .removed) { - print("Removed city: \(diff.document.data())") - } - } - } - // [END listen_diffs] - } - - private func listenState() { - // [START listen_state] - db.collection("cities").whereField("state", isEqualTo: "CA") - .addSnapshotListener { querySnapshot, error in - guard let snapshot = querySnapshot else { - print("Error fetching documents: \(error!)") - return - } - snapshot.documentChanges.forEach { diff in - if (diff.type == .added) { - print("New city: \(diff.document.data())") - } - } - - if !snapshot.metadata.isFromCache { - print("Synced with server state.") - } - } - // [END listen_state] - } - - private func detachListener() { - // [START detach_listener] - let listener = db.collection("cities").addSnapshotListener { querySnapshot, error in - // [START_EXCLUDE] - // [END_EXCLUDE] + if !snapshot.metadata.isFromCache { + print("Synced with server state.") } + } + // [END listen_state] + } - // ... - - // Stop listening to changes - listener.remove() - // [END detach_listener] - } - - private func handleListenErrors() { - // [START handle_listen_errors] - db.collection("cities") - .addSnapshotListener { querySnapshot, error in - if let error = error { - print("Error retreiving collection: \(error)") - } - } - // [END handle_listen_errors] - } - - // ======================================================================================= - // ======== https://firebase.google.com/preview/firestore/client/query-data ============== - // ======================================================================================= - - private func simpleQueries() { - // [START simple_queries] - // Create a reference to the cities collection - let citiesRef = db.collection("cities") - - // Create a query against the collection. - let query = citiesRef.whereField("state", isEqualTo: "CA") - // [END simple_queries] - - // [START simple_query_not_equal] - let notEqualQuery = citiesRef.whereField("capital", isNotEqualTo: false) - // [END simple_query_not_equal] - - print(query) - } - - private func exampleFilters() { - let citiesRef = db.collection("cities") - - // [START example_filters] - let stateQuery = citiesRef.whereField("state", isEqualTo: "CA") - let populationQuery = citiesRef.whereField("population", isLessThan: 100000) - let nameQuery = citiesRef.whereField("name", isGreaterThanOrEqualTo: "San Francisco") - // [END example_filters] - } - - private func onlyCapitals() { - // [START only_capitals] - let capitalCities = db.collection("cities").whereField("capital", isEqualTo: true) - // [END only_capitals] - print(capitalCities) - } - - private func arrayContainsFilter() { - let citiesRef = db.collection("cities") - - // [START array_contains_filter] - citiesRef - .whereField("regions", arrayContains: "west_coast") - // [END array_contains_filter] - } - - private func chainFilters() { - let citiesRef = db.collection("cities") - - // [START chain_filters] - citiesRef - .whereField("state", isEqualTo: "CO") - .whereField("name", isEqualTo: "Denver") - citiesRef - .whereField("state", isEqualTo: "CA") - .whereField("population", isLessThan: 1000000) - // [END chain_filters] - } - - private func validRangeFilters() { - let citiesRef = db.collection("cities") - - // [START valid_range_filters] - citiesRef - .whereField("state", isGreaterThanOrEqualTo: "CA") - .whereField("state", isLessThanOrEqualTo: "IN") - citiesRef - .whereField("state", isEqualTo: "CA") - .whereField("population", isGreaterThan: 1000000) - // [END valid_range_filters] - } - - private func invalidRangeFilters() throws { - let citiesRef = db.collection("cities") - - // [START invalid_range_filters] - citiesRef - .whereField("state", isGreaterThanOrEqualTo: "CA") - .whereField("population", isGreaterThan: 1000000) - // [END invalid_range_filters] - } - - private func orderAndLimit() { - let citiesRef = db.collection("cities") - - // [START order_and_limit] - citiesRef.order(by: "name").limit(to: 3) - // [END order_and_limit] - } - - private func orderAndLimitDesc() { - let citiesRef = db.collection("cities") - - // [START order_and_limit_desc] - citiesRef.order(by: "name", descending: true).limit(to: 3) - // [END order_and_limit_desc] - } - - private func orderMultiple() { - let citiesRef = db.collection("cities") - - // [START order_multiple] - citiesRef - .order(by: "state") - .order(by: "population", descending: true) - // [END order_multiple] - } - - private func filterAndOrder() { - let citiesRef = db.collection("cities") - - // [START filter_and_order] - citiesRef - .whereField("population", isGreaterThan: 100000) - .order(by: "population") - .limit(to: 2) - // [END filter_and_order] - } - - private func validFilterAndOrder() { - let citiesRef = db.collection("cities") - - // [START valid_filter_and_order] - citiesRef - .whereField("population", isGreaterThan: 100000) - .order(by: "population") - // [END valid_filter_and_order] - } - - private func invalidFilterAndOrder() throws { - let citiesRef = db.collection("cities") - - // [START invalid_filter_and_order] - citiesRef - .whereField("population", isGreaterThan: 100000) - .order(by: "country") - // [END invalid_filter_and_order] - } - - private func arrayContainsAnyQueries() { - // [START array_contains_any_filter] - let citiesRef = db.collection("cities") - citiesRef.whereField("regions", arrayContainsAny: ["west_coast", "east_coast"]) - // [END array_contains_any_filter] - } - - private func inQueries() { - // [START in_filter] - let citiesRef = db.collection("cities") - - citiesRef.whereField("country", in: ["USA", "Japan"]) - // [END in_filter] - - // [START in_filter_with_array] - citiesRef.whereField("regions", in: [["west_coast"], ["east_coast"]]); - // [END in_filter_with_array] - - // [START not_in_filter] - citiesRef.whereField("country", notIn: ["USA", "Japan"]) - // [END not_in_filter] + private func detachListener() { + // [START detach_listener] + let listener = db.collection("cities").addSnapshotListener { querySnapshot, error in + // [START_EXCLUDE] + // [END_EXCLUDE] } - // ======================================================================================= - // ====== https://firebase.google.com/preview/firestore/client/enable-offline ============ - // ======================================================================================= - - private func enableOffline() { - // [START enable_offline] - let settings = FirestoreSettings() - settings.isPersistenceEnabled = true + // ... - // Any additional options - // ... - - // Enable offline data persistence - let db = Firestore.firestore() - db.settings = settings - // [END enable_offline] - } - - private func listenToOffline() { - let db = Firestore.firestore() - // [START listen_to_offline] - // Listen to metadata updates to receive a server snapshot even if - // the data is the same as the cached data. - db.collection("cities").whereField("state", isEqualTo: "CA") - .addSnapshotListener(includeMetadataChanges: true) { querySnapshot, error in - guard let snapshot = querySnapshot else { - print("Error retreiving snapshot: \(error!)") - return - } - - for diff in snapshot.documentChanges { - if diff.type == .added { - print("New city: \(diff.document.data())") - } - } - - let source = snapshot.metadata.isFromCache ? "local cache" : "server" - print("Metadata: Data fetched from \(source)") - } - // [END listen_to_offline] - } + // Stop listening to changes + listener.remove() + // [END detach_listener] + } - private func toggleOffline() { - // [START disable_network] - Firestore.firestore().disableNetwork { (error) in - // Do offline things - // ... + private func handleListenErrors() { + // [START handle_listen_errors] + db.collection("cities") + .addSnapshotListener { querySnapshot, error in + if let error = error { + print("Error retreiving collection: \(error)") } - // [END disable_network] - - // [START enable_network] - Firestore.firestore().enableNetwork { (error) in - // Do online things - // ... + } + // [END handle_listen_errors] + } + + // ======================================================================================= + // ======== https://firebase.google.com/preview/firestore/client/query-data ============== + // ======================================================================================= + + private func simpleQueries() { + // [START simple_queries] + // Create a reference to the cities collection + let citiesRef = db.collection("cities") + + // Create a query against the collection. + let query = citiesRef.whereField("state", isEqualTo: "CA") + // [END simple_queries] + + // [START simple_query_not_equal] + let notEqualQuery = citiesRef.whereField("capital", isNotEqualTo: false) + // [END simple_query_not_equal] + + print(query) + } + + private func exampleFilters() { + let citiesRef = db.collection("cities") + + // [START example_filters] + let stateQuery = citiesRef.whereField("state", isEqualTo: "CA") + let populationQuery = citiesRef.whereField("population", isLessThan: 100000) + let nameQuery = citiesRef.whereField("name", isGreaterThanOrEqualTo: "San Francisco") + // [END example_filters] + } + + private func onlyCapitals() { + // [START only_capitals] + let capitalCities = db.collection("cities").whereField("capital", isEqualTo: true) + // [END only_capitals] + print(capitalCities) + } + + private func arrayContainsFilter() { + let citiesRef = db.collection("cities") + + // [START array_contains_filter] + citiesRef + .whereField("regions", arrayContains: "west_coast") + // [END array_contains_filter] + } + + private func chainFilters() { + let citiesRef = db.collection("cities") + + // [START chain_filters] + citiesRef + .whereField("state", isEqualTo: "CO") + .whereField("name", isEqualTo: "Denver") + citiesRef + .whereField("state", isEqualTo: "CA") + .whereField("population", isLessThan: 1000000) + // [END chain_filters] + } + + private func validRangeFilters() { + let citiesRef = db.collection("cities") + + // [START valid_range_filters] + citiesRef + .whereField("state", isGreaterThanOrEqualTo: "CA") + .whereField("state", isLessThanOrEqualTo: "IN") + citiesRef + .whereField("state", isEqualTo: "CA") + .whereField("population", isGreaterThan: 1000000) + // [END valid_range_filters] + } + + private func invalidRangeFilters() throws { + let citiesRef = db.collection("cities") + + // [START invalid_range_filters] + citiesRef + .whereField("state", isGreaterThanOrEqualTo: "CA") + .whereField("population", isGreaterThan: 1000000) + // [END invalid_range_filters] + } + + private func orderAndLimit() { + let citiesRef = db.collection("cities") + + // [START order_and_limit] + citiesRef.order(by: "name").limit(to: 3) + // [END order_and_limit] + } + + private func orderAndLimitDesc() { + let citiesRef = db.collection("cities") + + // [START order_and_limit_desc] + citiesRef.order(by: "name", descending: true).limit(to: 3) + // [END order_and_limit_desc] + } + + private func orderMultiple() { + let citiesRef = db.collection("cities") + + // [START order_multiple] + citiesRef + .order(by: "state") + .order(by: "population", descending: true) + // [END order_multiple] + } + + private func filterAndOrder() { + let citiesRef = db.collection("cities") + + // [START filter_and_order] + citiesRef + .whereField("population", isGreaterThan: 100000) + .order(by: "population") + .limit(to: 2) + // [END filter_and_order] + } + + private func validFilterAndOrder() { + let citiesRef = db.collection("cities") + + // [START valid_filter_and_order] + citiesRef + .whereField("population", isGreaterThan: 100000) + .order(by: "population") + // [END valid_filter_and_order] + } + + private func invalidFilterAndOrder() throws { + let citiesRef = db.collection("cities") + + // [START invalid_filter_and_order] + citiesRef + .whereField("population", isGreaterThan: 100000) + .order(by: "country") + // [END invalid_filter_and_order] + } + + private func arrayContainsAnyQueries() { + // [START array_contains_any_filter] + let citiesRef = db.collection("cities") + citiesRef.whereField("regions", arrayContainsAny: ["west_coast", "east_coast"]) + // [END array_contains_any_filter] + } + + private func inQueries() { + // [START in_filter] + let citiesRef = db.collection("cities") + + citiesRef.whereField("country", in: ["USA", "Japan"]) + // [END in_filter] + + // [START in_filter_with_array] + citiesRef.whereField("regions", in: [["west_coast"], ["east_coast"]]) + // [END in_filter_with_array] + + // [START not_in_filter] + citiesRef.whereField("country", notIn: ["USA", "Japan"]) + // [END not_in_filter] + } + + // ======================================================================================= + // ====== https://firebase.google.com/preview/firestore/client/enable-offline ============ + // ======================================================================================= + + private func enableOffline() { + // [START enable_offline] + let settings = FirestoreSettings() + + // Use memory-only cache + settings.cacheSettings = + MemoryCacheSettings(garbageCollectorSettings: MemoryLRUGCSettings()) + + // Use persistent disk cache, with 100 MB cache size + settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber) + + // Any additional options + // ... + + // Enable offline data persistence + let db = Firestore.firestore() + db.settings = settings + // [END enable_offline] + } + + private func listenToOffline() { + let db = Firestore.firestore() + // [START listen_to_offline] + // Listen to metadata updates to receive a server snapshot even if + // the data is the same as the cached data. + db.collection("cities").whereField("state", isEqualTo: "CA") + .addSnapshotListener(includeMetadataChanges: true) { querySnapshot, error in + guard let snapshot = querySnapshot else { + print("Error retreiving snapshot: \(error!)") + return } - // [END enable_network] - } - // ======================================================================================= - // ====== https://firebase.google.com/preview/firestore/client/cursors =================== - // ======================================================================================= - - private func simpleCursor() { - let db = Firestore.firestore() - - // [START cursor_greater_than] - // Get all cities with population over one million, ordered by population. - db.collection("cities") - .order(by: "population") - .start(at: [1000000]) - // [END cursor_greater_than] - - // [START cursor_less_than] - // Get all cities with population less than one million, ordered by population. - db.collection("cities") - .order(by: "population") - .end(at: [1000000]) - // [END cursor_less_than] - } - - private func snapshotCursor() { - let db = Firestore.firestore() - - // [START snapshot_cursor] - db.collection("cities") - .document("SF") - .addSnapshotListener { (document, error) in - guard let document = document else { - print("Error retreving cities: \(error.debugDescription)") - return - } - - // Get all cities with a population greater than or equal to San Francisco. - let sfSizeOrBigger = db.collection("cities") - .order(by: "population") - .start(atDocument: document) + for diff in snapshot.documentChanges { + if diff.type == .added { + print("New city: \(diff.document.data())") + } } - // [END snapshot_cursor] - } - private func paginate() { - let db = Firestore.firestore() - - // [START paginate] - // Construct query for first 25 cities, ordered by population - let first = db.collection("cities") - .order(by: "population") - .limit(to: 25) - - first.addSnapshotListener { (snapshot, error) in - guard let snapshot = snapshot else { - print("Error retreving cities: \(error.debugDescription)") - return - } - - guard let lastSnapshot = snapshot.documents.last else { - // The collection is empty. - return - } - - // Construct a new query starting after this document, - // retrieving the next 25 cities. - let next = db.collection("cities") - .order(by: "population") - .start(afterDocument: lastSnapshot) - - // Use the query for pagination. - // ... - } - // [END paginate] - } - - private func multiCursor() { - let db = Firestore.firestore() - - // [START multi_cursor] - // Will return all Springfields - db.collection("cities") - .order(by: "name") - .order(by: "state") - .start(at: ["Springfield"]) - - // Will return "Springfield, Missouri" and "Springfield, Wisconsin" - db.collection("cities") - .order(by: "name") - .order(by: "state") - .start(at: ["Springfield", "Missouri"]) - // [END multi_cursor] - } - - private func collectionGroupQuery() { - // [START fs_collection_group_query] - db.collectionGroup("landmarks").whereField("type", isEqualTo: "museum").getDocuments { (snapshot, error) in - // [START_EXCLUDE] - print(snapshot?.documents.count ?? 0) - // [END_EXCLUDE] + let source = snapshot.metadata.isFromCache ? "local cache" : "server" + print("Metadata: Data fetched from \(source)") + } + // [END listen_to_offline] + } + + private func toggleOffline() { + // [START disable_network] + Firestore.firestore().disableNetwork { (error) in + // Do offline things + // ... + } + // [END disable_network] + + // [START enable_network] + Firestore.firestore().enableNetwork { (error) in + // Do online things + // ... + } + // [END enable_network] + } + + // ======================================================================================= + // ====== https://firebase.google.com/preview/firestore/client/cursors =================== + // ======================================================================================= + + private func simpleCursor() { + let db = Firestore.firestore() + + // [START cursor_greater_than] + // Get all cities with population over one million, ordered by population. + db.collection("cities") + .order(by: "population") + .start(at: [1000000]) + // [END cursor_greater_than] + + // [START cursor_less_than] + // Get all cities with population less than one million, ordered by population. + db.collection("cities") + .order(by: "population") + .end(at: [1000000]) + // [END cursor_less_than] + } + + private func snapshotCursor() { + let db = Firestore.firestore() + + // [START snapshot_cursor] + db.collection("cities") + .document("SF") + .addSnapshotListener { (document, error) in + guard let document = document else { + print("Error retreving cities: \(error.debugDescription)") + return } - // [END fs_collection_group_query] - } - private func emulatorSettings() { - // [START fs_emulator_connect] - let settings = Firestore.firestore().settings - settings.host = "localhost:8080" - settings.isPersistenceEnabled = false - settings.isSSLEnabled = false - Firestore.firestore().settings = settings - // [END fs_emulator_connect] - } - - // MARK: Aggregation queries - private func countAggregateCollection() async { - // [START count_aggregate_collection] - let query = db.collection("cities") - let countQuery = query.count - do { - let snapshot = try await countQuery.getAggregation(source: .server) - print(snapshot.count) - } catch { - print(error); - } - // [END count_aggregate_collection] - } + // Get all cities with a population greater than or equal to San Francisco. + let sfSizeOrBigger = db.collection("cities") + .order(by: "population") + .start(atDocument: document) + } + // [END snapshot_cursor] + } + + private func paginate() { + let db = Firestore.firestore() + + // [START paginate] + // Construct query for first 25 cities, ordered by population + let first = db.collection("cities") + .order(by: "population") + .limit(to: 25) + + first.addSnapshotListener { (snapshot, error) in + guard let snapshot = snapshot else { + print("Error retreving cities: \(error.debugDescription)") + return + } - private func countAggregateQuery() async { - // [START count_aggregate_query] - let query = db.collection("cities").whereField("state", isEqualTo: "CA") - let countQuery = query.count - do { - let snapshot = try await countQuery.getAggregation(source: .server) - print(snapshot.count) - } catch { - print(error); - } - // [END count_aggregate_query] - } + guard let lastSnapshot = snapshot.documents.last else { + // The collection is empty. + return + } + // Construct a new query starting after this document, + // retrieving the next 25 cities. + let next = db.collection("cities") + .order(by: "population") + .start(afterDocument: lastSnapshot) + + // Use the query for pagination. + // ... + } + // [END paginate] + } + + private func multiCursor() { + let db = Firestore.firestore() + + // [START multi_cursor] + // Will return all Springfields + db.collection("cities") + .order(by: "name") + .order(by: "state") + .start(at: ["Springfield"]) + + // Will return "Springfield, Missouri" and "Springfield, Wisconsin" + db.collection("cities") + .order(by: "name") + .order(by: "state") + .start(at: ["Springfield", "Missouri"]) + // [END multi_cursor] + } + + private func collectionGroupQuery() { + // [START fs_collection_group_query] + db.collectionGroup("landmarks").whereField("type", isEqualTo: "museum").getDocuments { (snapshot, error) in + // [START_EXCLUDE] + print(snapshot?.documents.count ?? 0) + // [END_EXCLUDE] + } + // [END fs_collection_group_query] + } + + private func emulatorSettings() { + // [START fs_emulator_connect] + let settings = Firestore.firestore().settings + settings.host = "127.0.0.1:8080" + settings.cacheSettings = MemoryCacheSettings() + settings.isSSLEnabled = false + Firestore.firestore().settings = settings + // [END fs_emulator_connect] + } + + // MARK: Aggregation queries + private func countAggregateCollection() async { + // [START count_aggregate_collection] + let query = db.collection("cities") + let countQuery = query.count + do { + let snapshot = try await countQuery.getAggregation(source: .server) + print(snapshot.count) + } catch { + print(error) + } + // [END count_aggregate_collection] + } + + private func countAggregateQuery() async { + // [START count_aggregate_query] + let query = db.collection("cities").whereField("state", isEqualTo: "CA") + let countQuery = query.count + do { + let snapshot = try await countQuery.getAggregation(source: .server) + print(snapshot.count) + } catch { + print(error) + } + // [END count_aggregate_query] + } + + private func orQuery() { + // [START or_query] + let query = db.collection("cities").whereFilter(Filter.andFilter([ + Filter.whereField("state", isEqualTo: "CA"), + Filter.orFilter([ + Filter.whereField("capital", isEqualTo: true), + Filter.whereField("population", isGreaterThanOrEqualTo: 1000000) + ]) + ])) + // [END or_query] + } + + private func orQueryDisjunctions() { + let collection = db.collection("cities") + + // [START one_disjunction] + collection.whereField("a", isEqualTo: 1) + // [END one_disjunction] + + // [START two_disjunctions] + collection.whereFilter(Filter.orFilter([ + Filter.whereField("a", isEqualTo: 1), + Filter.whereField("b", isEqualTo: 2) + ])) + // [END two_disjunctions] + + // [START four_disjunctions] + collection.whereFilter(Filter.orFilter([ + Filter.andFilter([ + Filter.whereField("a", isEqualTo: 1), + Filter.whereField("c", isEqualTo: 3) + ]), + Filter.andFilter([ + Filter.whereField("a", isEqualTo: 1), + Filter.whereField("d", isEqualTo: 4) + ]), + Filter.andFilter([ + Filter.whereField("b", isEqualTo: 2), + Filter.whereField("c", isEqualTo: 3) + ]), + Filter.andFilter([ + Filter.whereField("b", isEqualTo: 2), + Filter.whereField("d", isEqualTo: 4) + ]) + ])) + // [END four_disjunctions] + + // [START four_disjunctions_compact] + collection.whereFilter(Filter.andFilter([ + Filter.orFilter([ + Filter.whereField("a", isEqualTo: 1), + Filter.whereField("b", isEqualTo: 2) + ]), + Filter.orFilter([ + Filter.whereField("c", isEqualTo: 3), + Filter.whereField("d", isEqualTo: 4) + ]), + ])) + // [END four_disjunctions_compact] + + // [START 20_disjunctions] + collection.whereFilter(Filter.orFilter([ + Filter.whereField("a", in: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), + Filter.whereField("b", in: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + ])) + // [END 20_disjunctions] + + // [START 10_disjunctions] + collection.whereFilter(Filter.andFilter([ + Filter.whereField("a", in: [1, 2, 3, 4, 5]), + Filter.orFilter([ + Filter.whereField("b", isEqualTo: 2), + Filter.whereField("c", isEqualTo: 3) + ]) + ])) + // [END 10_disjunctions] + } + + // This method crashes, so don't include it in the smoketest. + func illegalDisjunctions() { + let collection = db.collection("cities") + + // [START 50_disjunctions] + collection.whereFilter(Filter.andFilter([ + Filter.whereField("a", in: [1, 2, 3, 4, 5]), + Filter.whereField("b", in: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + ])) + // [END 50_disjunctions] + } + + private func sumAggregateCollection() async { + // [START sum_aggregate_collection] + let query = db.collection("cities") + let aggregateQuery = query.aggregate([AggregateField.sum("population")]) + do { + let snapshot = try await aggregateQuery.getAggregation(source: .server) + print(snapshot.get(AggregateField.sum("population"))) + } catch { + print(error) + } + // [END sum_aggregate_collection] + } + + private func sumAggregateQuery() async { + // [START sum_aggregate_query] + let query = db.collection("cities").whereField("capital", isEqualTo: true) + let aggregateQuery = query.aggregate([AggregateField.sum("population")]) + do { + let snapshot = try await aggregateQuery.getAggregation(source: .server) + print(snapshot.get(AggregateField.sum("population"))) + } catch { + print(error) + } + // [END sum_aggregate_query] + } + + private func averageAggregateCollection() async { + // [START average_aggregate_collection] + let query = db.collection("cities") + let aggregateQuery = query.aggregate([AggregateField.average("population")]) + do { + let snapshot = try await aggregateQuery.getAggregation(source: .server) + print(snapshot.get(AggregateField.average("population"))) + } catch { + print(error) + } + // [END average_aggregate_collection] + } + + private func averageAggregateQuery() async { + // [START average_aggregate_query] + let query = db.collection("cities").whereField("capital", isEqualTo: true) + let aggregateQuery = query.aggregate([AggregateField.average("population")]) + do { + let snapshot = try await aggregateQuery.getAggregation(source: .server) + print(snapshot.get(AggregateField.average("population"))) + } catch { + print(error) + } + // [END average_aggregate_query] + } + + private func multiAggregateCollection() async { + // [START multi_aggregate_collection] + let query = db.collection("cities") + let aggregateQuery = query.aggregate([ + AggregateField.count(), + AggregateField.sum("population"), + AggregateField.average("population")]) + do { + let snapshot = try await aggregateQuery.getAggregation(source: .server) + print("Count: \(snapshot.get(AggregateField.count()))") + print("Sum: \(snapshot.get(AggregateField.sum("population")))") + print("Average: \(snapshot.get(AggregateField.average("population")))") + } catch { + print(error) + } + // [END multi_aggregate_collection] + } } // [START codable_struct] public struct City: Codable { - let name: String - let state: String? - let country: String? - let isCapital: Bool? - let population: Int64? - - enum CodingKeys: String, CodingKey { - case name - case state - case country - case isCapital = "capital" - case population - } + let name: String + let state: String? + let country: String? + let isCapital: Bool? + let population: Int64? + + enum CodingKeys: String, CodingKey { + case name + case state + case country + case isCapital = "capital" + case population + } } // [END codable_struct] diff --git a/firoptions/FiroptionConfiguration.xcodeproj/project.pbxproj b/firoptions/FiroptionConfiguration.xcodeproj/project.pbxproj index 1572b257..6c7323c0 100644 --- a/firoptions/FiroptionConfiguration.xcodeproj/project.pbxproj +++ b/firoptions/FiroptionConfiguration.xcodeproj/project.pbxproj @@ -3,10 +3,16 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ + 8D7951AC2D28AF88000FD694 /* FirebaseAnalytics in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951AB2D28AF88000FD694 /* FirebaseAnalytics */; }; + 8D7951AE2D28AF88000FD694 /* FirebaseCore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951AD2D28AF88000FD694 /* FirebaseCore */; }; + 8D7951B02D28AF88000FD694 /* FirebaseDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951AF2D28AF88000FD694 /* FirebaseDatabase */; }; + 8D7951B22D28AFF4000FD694 /* FirebaseAnalytics in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951B12D28AFF4000FD694 /* FirebaseAnalytics */; }; + 8D7951B42D28AFF4000FD694 /* FirebaseCore in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951B32D28AFF4000FD694 /* FirebaseCore */; }; + 8D7951B62D28B003000FD694 /* FirebaseDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951B52D28B003000FD694 /* FirebaseDatabase */; }; 8DFC20162410844B004392AD /* AnalyticsHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 8DFC20152410844B004392AD /* AnalyticsHelper.m */; }; A19F764427EDED14002DE108 /* ISImpressionData.m in Sources */ = {isa = PBXBuildFile; fileRef = A19F764027EDED14002DE108 /* ISImpressionData.m */; }; A19F764527EDED14002DE108 /* MAAd.m in Sources */ = {isa = PBXBuildFile; fileRef = A19F764327EDED14002DE108 /* MAAd.m */; }; @@ -51,6 +57,9 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951B02D28AF88000FD694 /* FirebaseDatabase in Frameworks */, + 8D7951AE2D28AF88000FD694 /* FirebaseCore in Frameworks */, + 8D7951AC2D28AF88000FD694 /* FirebaseAnalytics in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -58,17 +67,20 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951B62D28B003000FD694 /* FirebaseDatabase in Frameworks */, + 8D7951B42D28AFF4000FD694 /* FirebaseCore in Frameworks */, + 8D7951B22D28AFF4000FD694 /* FirebaseAnalytics in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 868938E40019DC0FEF0F5F30 /* Pods */ = { + 8D7951AA2D28AF88000FD694 /* Frameworks */ = { isa = PBXGroup; children = ( ); - path = Pods; + name = Frameworks; sourceTree = ""; }; EFEC9D561E01BF310021BDF9 = { @@ -76,8 +88,8 @@ children = ( EFEC9D9B1E01EEB60021BDF9 /* Dev */, EFEC9D611E01BF310021BDF9 /* FiroptionConfiguration */, + 8D7951AA2D28AF88000FD694 /* Frameworks */, EFEC9D601E01BF310021BDF9 /* Products */, - 868938E40019DC0FEF0F5F30 /* Pods */, ); sourceTree = ""; }; @@ -163,8 +175,9 @@ EFEC9D571E01BF310021BDF9 /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 0820; - LastUpgradeCheck = 1130; + LastUpgradeCheck = 1610; ORGANIZATIONNAME = Google; TargetAttributes = { EFEC9D5E1E01BF310021BDF9 = { @@ -189,6 +202,9 @@ Base, ); mainGroup = EFEC9D561E01BF310021BDF9; + packageReferences = ( + 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = EFEC9D601E01BF310021BDF9 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -293,6 +309,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -303,6 +320,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -317,7 +335,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.2; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -351,6 +369,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -361,6 +380,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -369,10 +389,11 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.2; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -385,7 +406,10 @@ CLANG_ENABLE_MODULES = YES; DEVELOPMENT_TEAM = EQHXZ8M8AV; INFOPLIST_FILE = FiroptionConfiguration/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.devrel.FiroptionConfiguration; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "FiroptionConfiguration/FiroptionConfiguration-Bridging-Header.h"; @@ -401,7 +425,10 @@ CLANG_ENABLE_MODULES = YES; DEVELOPMENT_TEAM = EQHXZ8M8AV; INFOPLIST_FILE = FiroptionConfiguration/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.devrel.FiroptionConfiguration; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "FiroptionConfiguration/FiroptionConfiguration-Bridging-Header.h"; @@ -415,7 +442,10 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; DEVELOPMENT_TEAM = EQHXZ8M8AV; INFOPLIST_FILE = "$(SRCROOT)/FiroptionConfiguration/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.devrel.FiroptionConfigurationDev; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.2; @@ -428,7 +458,10 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; DEVELOPMENT_TEAM = EQHXZ8M8AV; INFOPLIST_FILE = "$(SRCROOT)/FiroptionConfiguration/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.devrel.FiroptionConfigurationDev; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 4.2; @@ -466,6 +499,50 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7951AB2D28AF88000FD694 /* FirebaseAnalytics */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAnalytics; + }; + 8D7951AD2D28AF88000FD694 /* FirebaseCore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCore; + }; + 8D7951AF2D28AF88000FD694 /* FirebaseDatabase */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseDatabase; + }; + 8D7951B12D28AFF4000FD694 /* FirebaseAnalytics */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAnalytics; + }; + 8D7951B32D28AFF4000FD694 /* FirebaseCore */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseCore; + }; + 8D7951B52D28B003000FD694 /* FirebaseDatabase */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951A92D28AF6D000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseDatabase; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = EFEC9D571E01BF310021BDF9 /* Project object */; } diff --git a/firoptions/FiroptionConfiguration/AppDelegate.swift b/firoptions/FiroptionConfiguration/AppDelegate.swift index b3e1e5fc..1311dfcc 100644 --- a/firoptions/FiroptionConfiguration/AppDelegate.swift +++ b/firoptions/FiroptionConfiguration/AppDelegate.swift @@ -15,7 +15,8 @@ // import UIKit -import Firebase +import FirebaseCore +import FirebaseDatabase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { @@ -53,11 +54,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // The other options are not mandatory, but may be required // for specific Firebase products. secondaryOptions.bundleID = "com.google.firebase.devrel.FiroptionConfiguration" - secondaryOptions.trackingID = "UA-12345678-1" secondaryOptions.clientID = "27992087142-ola6qe637ulk8780vl8mo5vogegkm23n.apps.googleusercontent.com" secondaryOptions.databaseURL = "https://myproject.firebaseio.com" secondaryOptions.storageBucket = "myproject.appspot.com" - secondaryOptions.androidClientID = "12345.apps.googleusercontent.com" secondaryOptions.deepLinkURLScheme = "myapp://" secondaryOptions.storageBucket = "projectid-12345.appspot.com" secondaryOptions.appGroupID = nil diff --git a/firoptions/Podfile b/firoptions/Podfile deleted file mode 100644 index a062e3de..00000000 --- a/firoptions/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -# Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' - -target 'FiroptionConfiguration' do - # Comment the next line if you're not using Swift and don't want to use dynamic frameworks - use_frameworks! - - # Pods for FiroptionConfiguration - pod 'Firebase/Analytics' - pod 'Firebase/Core' - pod 'Firebase/Database' - -end diff --git a/firoptions/Podfile.lock b/firoptions/Podfile.lock deleted file mode 100644 index dac07ae7..00000000 --- a/firoptions/Podfile.lock +++ /dev/null @@ -1,139 +0,0 @@ -PODS: - - Firebase/Analytics (9.6.0): - - Firebase/Core - - Firebase/Core (9.6.0): - - Firebase/CoreOnly - - FirebaseAnalytics (~> 9.6.0) - - Firebase/CoreOnly (9.6.0): - - FirebaseCore (= 9.6.0) - - Firebase/Database (9.6.0): - - Firebase/CoreOnly - - FirebaseDatabase (~> 9.6.0) - - FirebaseAnalytics (9.6.0): - - FirebaseAnalytics/AdIdSupport (= 9.6.0) - - FirebaseCore (~> 9.0) - - FirebaseInstallations (~> 9.0) - - GoogleUtilities/AppDelegateSwizzler (~> 7.7) - - GoogleUtilities/MethodSwizzler (~> 7.7) - - GoogleUtilities/Network (~> 7.7) - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - nanopb (< 2.30910.0, >= 2.30908.0) - - FirebaseAnalytics/AdIdSupport (9.6.0): - - FirebaseCore (~> 9.0) - - FirebaseInstallations (~> 9.0) - - GoogleAppMeasurement (= 9.6.0) - - GoogleUtilities/AppDelegateSwizzler (~> 7.7) - - GoogleUtilities/MethodSwizzler (~> 7.7) - - GoogleUtilities/Network (~> 7.7) - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - nanopb (< 2.30910.0, >= 2.30908.0) - - FirebaseCore (9.6.0): - - FirebaseCoreDiagnostics (~> 9.0) - - FirebaseCoreInternal (~> 9.0) - - GoogleUtilities/Environment (~> 7.7) - - GoogleUtilities/Logger (~> 7.7) - - FirebaseCoreDiagnostics (9.6.0): - - GoogleDataTransport (< 10.0.0, >= 9.1.4) - - GoogleUtilities/Environment (~> 7.7) - - GoogleUtilities/Logger (~> 7.7) - - nanopb (< 2.30910.0, >= 2.30908.0) - - FirebaseCoreInternal (9.6.0): - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - FirebaseDatabase (9.6.0): - - FirebaseCore (~> 9.0) - - leveldb-library (~> 1.22) - - FirebaseInstallations (9.6.0): - - FirebaseCore (~> 9.0) - - GoogleUtilities/Environment (~> 7.7) - - GoogleUtilities/UserDefaults (~> 7.7) - - PromisesObjC (~> 2.1) - - GoogleAppMeasurement (9.6.0): - - GoogleAppMeasurement/AdIdSupport (= 9.6.0) - - GoogleUtilities/AppDelegateSwizzler (~> 7.7) - - GoogleUtilities/MethodSwizzler (~> 7.7) - - GoogleUtilities/Network (~> 7.7) - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - nanopb (< 2.30910.0, >= 2.30908.0) - - GoogleAppMeasurement/AdIdSupport (9.6.0): - - GoogleAppMeasurement/WithoutAdIdSupport (= 9.6.0) - - GoogleUtilities/AppDelegateSwizzler (~> 7.7) - - GoogleUtilities/MethodSwizzler (~> 7.7) - - GoogleUtilities/Network (~> 7.7) - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - nanopb (< 2.30910.0, >= 2.30908.0) - - GoogleAppMeasurement/WithoutAdIdSupport (9.6.0): - - GoogleUtilities/AppDelegateSwizzler (~> 7.7) - - GoogleUtilities/MethodSwizzler (~> 7.7) - - GoogleUtilities/Network (~> 7.7) - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - nanopb (< 2.30910.0, >= 2.30908.0) - - GoogleDataTransport (9.2.0): - - GoogleUtilities/Environment (~> 7.7) - - nanopb (< 2.30910.0, >= 2.30908.0) - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/AppDelegateSwizzler (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/Logger - - GoogleUtilities/Network - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - GoogleUtilities/MethodSwizzler (7.10.0): - - GoogleUtilities/Logger - - GoogleUtilities/Network (7.10.0): - - GoogleUtilities/Logger - - "GoogleUtilities/NSData+zlib" - - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GoogleUtilities/Reachability (7.10.0): - - GoogleUtilities/Logger - - GoogleUtilities/UserDefaults (7.10.0): - - GoogleUtilities/Logger - - leveldb-library (1.22.1) - - nanopb (2.30909.0): - - nanopb/decode (= 2.30909.0) - - nanopb/encode (= 2.30909.0) - - nanopb/decode (2.30909.0) - - nanopb/encode (2.30909.0) - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - Firebase/Analytics - - Firebase/Core - - Firebase/Database - -SPEC REPOS: - trunk: - - Firebase - - FirebaseAnalytics - - FirebaseCore - - FirebaseCoreDiagnostics - - FirebaseCoreInternal - - FirebaseDatabase - - FirebaseInstallations - - GoogleAppMeasurement - - GoogleDataTransport - - GoogleUtilities - - leveldb-library - - nanopb - - PromisesObjC - -SPEC CHECKSUMS: - Firebase: 5ae8b7cf8efce559a653aef0ad95bab3f427c351 - FirebaseAnalytics: 89ad762c6c3852a685794174757e2c60a36b6a82 - FirebaseCore: 2082fffcd855f95f883c0a1641133eb9bbe76d40 - FirebaseCoreDiagnostics: 99a495094b10a57eeb3ae8efa1665700ad0bdaa6 - FirebaseCoreInternal: bca76517fe1ed381e989f5e7d8abb0da8d85bed3 - FirebaseDatabase: 3de19e533a73d45e25917b46aafe1dd344ec8119 - FirebaseInstallations: 0a115432c4e223c5ab20b0dbbe4cbefa793a0e8e - GoogleAppMeasurement: 6de2b1a69e4326eb82ee05d138f6a5cb7311bcb1 - GoogleDataTransport: 1c8145da7117bd68bbbed00cf304edb6a24de00f - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - leveldb-library: 50c7b45cbd7bf543c81a468fe557a16ae3db8729 - nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 637f4cec311becce3d9f62d24448342df688ce41 - -COCOAPODS: 1.11.3 diff --git a/functions/FunctionsExample.xcodeproj/project.pbxproj b/functions/FunctionsExample.xcodeproj/project.pbxproj index 54bcb58e..207b4f35 100644 --- a/functions/FunctionsExample.xcodeproj/project.pbxproj +++ b/functions/FunctionsExample.xcodeproj/project.pbxproj @@ -3,10 +3,12 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ + 8D7951BA2D28B078000FD694 /* FirebaseFunctions in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951B92D28B078000FD694 /* FirebaseFunctions */; }; + 8D7951BC2D28B0C4000FD694 /* FirebaseFunctions in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951BB2D28B0C4000FD694 /* FirebaseFunctions */; }; 8D8FA34322F4CAB100213E06 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D8FA34222F4CAB100213E06 /* AppDelegate.m */; }; 8D8FA34622F4CAB100213E06 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D8FA34522F4CAB100213E06 /* ViewController.m */; }; 8D8FA34922F4CAB100213E06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D8FA34722F4CAB100213E06 /* Main.storyboard */; }; @@ -45,6 +47,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951BC2D28B0C4000FD694 /* FirebaseFunctions in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -52,17 +55,26 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951BA2D28B078000FD694 /* FirebaseFunctions in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 8D7951B82D28B078000FD694 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; 8D8FA33522F4CAB100213E06 = { isa = PBXGroup; children = ( 8D8FA34022F4CAB100213E06 /* FunctionsExample */, 8D8FA35C22F4CAF700213E06 /* FunctionsExampleSwift */, + 8D7951B82D28B078000FD694 /* Frameworks */, 8D8FA33F22F4CAB100213E06 /* Products */, ); sourceTree = ""; @@ -148,8 +160,9 @@ 8D8FA33622F4CAB100213E06 /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 1020; - LastUpgradeCheck = 1020; + LastUpgradeCheck = 1610; ORGANIZATIONNAME = Firebase; TargetAttributes = { 8D8FA33D22F4CAB100213E06 = { @@ -169,6 +182,9 @@ Base, ); mainGroup = 8D8FA33522F4CAB100213E06; + packageReferences = ( + 8D7951B72D28B070000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 8D8FA33F22F4CAB100213E06 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -286,6 +302,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -297,6 +314,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -345,6 +363,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -356,6 +375,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -368,6 +388,7 @@ MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; VALIDATE_PRODUCT = YES; }; name = Release; @@ -473,6 +494,30 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7951B72D28B070000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7951B92D28B078000FD694 /* FirebaseFunctions */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951B72D28B070000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseFunctions; + }; + 8D7951BB2D28B0C4000FD694 /* FirebaseFunctions */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951B72D28B070000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseFunctions; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 8D8FA33622F4CAB100213E06 /* Project object */; } diff --git a/functions/FunctionsExample/ViewController.m b/functions/FunctionsExample/ViewController.m index 252746b3..43c0b699 100644 --- a/functions/FunctionsExample/ViewController.m +++ b/functions/FunctionsExample/ViewController.m @@ -31,7 +31,7 @@ - (void)viewDidLoad { - (void)emulatorSettings { // [START functions_emulator_connect] - [[FIRFunctions functions] useFunctionsEmulatorOrigin:@"http://localhost:5001"]; + [[FIRFunctions functions] useEmulatorWithHost:@"localhost" port:5001]; // [END functions_emulator_connect] } diff --git a/functions/FunctionsExampleSwift/ViewController.swift b/functions/FunctionsExampleSwift/ViewController.swift index 15a932d3..0a0c6c25 100644 --- a/functions/FunctionsExampleSwift/ViewController.swift +++ b/functions/FunctionsExampleSwift/ViewController.swift @@ -26,7 +26,7 @@ class ViewController: UIViewController { func emulatorSettings() { // [START functions_emulator_connect] - Functions.functions().useFunctionsEmulator(origin: "http://localhost:5001") + Functions.functions().useEmulator(withHost: "localhost", port: 5001) // [END functions_emulator_connect] } diff --git a/functions/Podfile b/functions/Podfile deleted file mode 100644 index 070ed351..00000000 --- a/functions/Podfile +++ /dev/null @@ -1,18 +0,0 @@ -# Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' - -target 'FunctionsExample' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - pod 'Firebase/Functions' - -end - -target 'FunctionsExampleSwift' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - pod 'Firebase/Functions' - -end diff --git a/functions/Podfile.lock b/functions/Podfile.lock deleted file mode 100644 index 71421364..00000000 --- a/functions/Podfile.lock +++ /dev/null @@ -1,69 +0,0 @@ -PODS: - - Firebase/CoreOnly (10.2.0): - - FirebaseCore (= 10.2.0) - - Firebase/Functions (10.2.0): - - Firebase/CoreOnly - - FirebaseFunctions (~> 10.2.0) - - FirebaseAppCheckInterop (10.2.0) - - FirebaseAuthInterop (10.2.0) - - FirebaseCore (10.2.0): - - FirebaseCoreInternal (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/Logger (~> 7.8) - - FirebaseCoreExtension (10.2.0): - - FirebaseCore (~> 10.0) - - FirebaseCoreInternal (10.2.0): - - "GoogleUtilities/NSData+zlib (~> 7.8)" - - FirebaseFunctions (10.2.0): - - FirebaseAppCheckInterop (~> 10.0) - - FirebaseAuthInterop (~> 10.0) - - FirebaseCore (~> 10.0) - - FirebaseCoreExtension (~> 10.0) - - FirebaseMessagingInterop (~> 10.0) - - FirebaseSharedSwift (~> 10.0) - - GTMSessionFetcher/Core (< 4.0, >= 2.1) - - FirebaseMessagingInterop (10.2.0) - - FirebaseSharedSwift (10.2.0) - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GTMSessionFetcher/Core (3.0.0) - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - Firebase/Functions - -SPEC REPOS: - trunk: - - Firebase - - FirebaseAppCheckInterop - - FirebaseAuthInterop - - FirebaseCore - - FirebaseCoreExtension - - FirebaseCoreInternal - - FirebaseFunctions - - FirebaseMessagingInterop - - FirebaseSharedSwift - - GoogleUtilities - - GTMSessionFetcher - - PromisesObjC - -SPEC CHECKSUMS: - Firebase: a3ea7eba4382afd83808376edb99acdaff078dcf - FirebaseAppCheckInterop: af164d9c623f82174e3ffa54394dee189587c601 - FirebaseAuthInterop: 027d42ca8fec84dc6151566479af05095a0bd5c0 - FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1 - FirebaseCoreExtension: d08b424832917cf13612021574399afbbedffeef - FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f - FirebaseFunctions: eaa208f64f2f179f0ab9b775fecdec07fdd74d90 - FirebaseMessagingInterop: b46e7fcf39c0e9b16841e258645a320a154af240 - FirebaseSharedSwift: a160b39d4ce77be922b3d6ff009099c7294e36e5 - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - GTMSessionFetcher: c1edebe64e9fb4e8f6415d018edf1fd3eac074a1 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 0bf21181414ed35c7e5fc96da7dd0f72b77e7b34 - -COCOAPODS: 1.11.3 diff --git a/inappmessaging/FIAMReference/FIAMReference.xcodeproj/project.pbxproj b/inappmessaging/FIAMReference/FIAMReference.xcodeproj/project.pbxproj index 7d111c20..0003f2ea 100644 --- a/inappmessaging/FIAMReference/FIAMReference.xcodeproj/project.pbxproj +++ b/inappmessaging/FIAMReference/FIAMReference.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -20,12 +20,11 @@ 3E64A7C32294513E003EE93A /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 3E64A7C12294513E003EE93A /* LaunchScreen.storyboard */; }; 3E64A7C9229456A3003EE93A /* CardActionFiamDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E64A7C8229456A3003EE93A /* CardActionFiamDelegate.swift */; }; 3E64A7D522946983003EE93A /* CardActionFiamDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 3E64A7D422946983003EE93A /* CardActionFiamDelegate.m */; }; - 7B57A0C81AD819D38114C0DA /* Pods_FIAMReferenceSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F5CB090B898D1808D8BFB45E /* Pods_FIAMReferenceSwift.framework */; }; - 9DC7047D28AC0715DA8758B9 /* Pods_FIAMReference.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0F31B861CDBF9DB7CD403440 /* Pods_FIAMReference.framework */; }; + 8D7951C02D2C8885000FD694 /* FirebaseInAppMessaging-Beta in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951BF2D2C8885000FD694 /* FirebaseInAppMessaging-Beta */; }; + 8D7951C22D2C888E000FD694 /* FirebaseInAppMessaging-Beta in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951C12D2C888E000FD694 /* FirebaseInAppMessaging-Beta */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ - 0F31B861CDBF9DB7CD403440 /* Pods_FIAMReference.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_FIAMReference.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3E64A798229376BB003EE93A /* FIAMReference.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = FIAMReference.app; sourceTree = BUILT_PRODUCTS_DIR; }; 3E64A79B229376BB003EE93A /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 3E64A79C229376BB003EE93A /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; @@ -46,11 +45,6 @@ 3E64A7C8229456A3003EE93A /* CardActionFiamDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CardActionFiamDelegate.swift; sourceTree = ""; }; 3E64A7D322946983003EE93A /* CardActionFiamDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CardActionFiamDelegate.h; sourceTree = ""; }; 3E64A7D422946983003EE93A /* CardActionFiamDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CardActionFiamDelegate.m; sourceTree = ""; }; - 60DA3A39F9552E8B37AD597C /* Pods-FIAMReferenceSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-FIAMReferenceSwift.release.xcconfig"; path = "Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift.release.xcconfig"; sourceTree = ""; }; - 8D026225BF1D8381A23B9CDD /* Pods-FIAMReferenceSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-FIAMReferenceSwift.debug.xcconfig"; path = "Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift.debug.xcconfig"; sourceTree = ""; }; - 9E2817EDB630021664AEF7F0 /* Pods-FIAMReference.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-FIAMReference.release.xcconfig"; path = "Target Support Files/Pods-FIAMReference/Pods-FIAMReference.release.xcconfig"; sourceTree = ""; }; - B20FEECC6333640D763A6374 /* Pods-FIAMReference.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-FIAMReference.debug.xcconfig"; path = "Target Support Files/Pods-FIAMReference/Pods-FIAMReference.debug.xcconfig"; sourceTree = ""; }; - F5CB090B898D1808D8BFB45E /* Pods_FIAMReferenceSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_FIAMReferenceSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -58,7 +52,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 9DC7047D28AC0715DA8758B9 /* Pods_FIAMReference.framework in Frameworks */, + 8D7951C02D2C8885000FD694 /* FirebaseInAppMessaging-Beta in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -66,7 +60,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 7B57A0C81AD819D38114C0DA /* Pods_FIAMReferenceSwift.framework in Frameworks */, + 8D7951C22D2C888E000FD694 /* FirebaseInAppMessaging-Beta in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -79,8 +73,6 @@ 3E64A79A229376BB003EE93A /* FIAMReference */, 3E64A7B72294513E003EE93A /* FIAMReferenceSwift */, 3E64A799229376BB003EE93A /* Products */, - CE6E66E48A82916264FE3F5B /* Pods */, - A53E5F3D908E32CBF3BBB4EC /* Frameworks */, ); sourceTree = ""; }; @@ -125,27 +117,6 @@ path = FIAMReferenceSwift; sourceTree = ""; }; - A53E5F3D908E32CBF3BBB4EC /* Frameworks */ = { - isa = PBXGroup; - children = ( - 0F31B861CDBF9DB7CD403440 /* Pods_FIAMReference.framework */, - F5CB090B898D1808D8BFB45E /* Pods_FIAMReferenceSwift.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - CE6E66E48A82916264FE3F5B /* Pods */ = { - isa = PBXGroup; - children = ( - B20FEECC6333640D763A6374 /* Pods-FIAMReference.debug.xcconfig */, - 9E2817EDB630021664AEF7F0 /* Pods-FIAMReference.release.xcconfig */, - 8D026225BF1D8381A23B9CDD /* Pods-FIAMReferenceSwift.debug.xcconfig */, - 60DA3A39F9552E8B37AD597C /* Pods-FIAMReferenceSwift.release.xcconfig */, - ); - name = Pods; - path = ../Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -153,12 +124,9 @@ isa = PBXNativeTarget; buildConfigurationList = 3E64A7AE229376BC003EE93A /* Build configuration list for PBXNativeTarget "FIAMReference" */; buildPhases = ( - 46E292585FA315EF59F64499 /* [CP] Check Pods Manifest.lock */, 3E64A794229376BB003EE93A /* Sources */, 3E64A795229376BB003EE93A /* Frameworks */, 3E64A796229376BB003EE93A /* Resources */, - 65339EA2723DC26D2F6AB3B9 /* [CP] Embed Pods Frameworks */, - C7965CB691942633E444DB3C /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -173,12 +141,9 @@ isa = PBXNativeTarget; buildConfigurationList = 3E64A7C72294513E003EE93A /* Build configuration list for PBXNativeTarget "FIAMReferenceSwift" */; buildPhases = ( - BBF5C5D44E878689104526D9 /* [CP] Check Pods Manifest.lock */, 3E64A7B22294513E003EE93A /* Sources */, 3E64A7B32294513E003EE93A /* Frameworks */, 3E64A7B42294513E003EE93A /* Resources */, - C45D95F46F4377C48D861896 /* [CP] Embed Pods Frameworks */, - 771EE35B3102DD3769ED7A38 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -195,8 +160,9 @@ 3E64A790229376BB003EE93A /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 1000; - LastUpgradeCheck = 1000; + LastUpgradeCheck = 1610; ORGANIZATIONNAME = Google; TargetAttributes = { 3E64A797229376BB003EE93A = { @@ -216,6 +182,9 @@ Base, ); mainGroup = 3E64A78F229376BB003EE93A; + packageReferences = ( + 8D7951BD2D2C887B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 3E64A799229376BB003EE93A /* Products */; projectDirPath = ""; projectRoot = ""; @@ -249,121 +218,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 46E292585FA315EF59F64499 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-FIAMReference-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 65339EA2723DC26D2F6AB3B9 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReference/Pods-FIAMReference-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReference/Pods-FIAMReference-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-FIAMReference/Pods-FIAMReference-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 771EE35B3102DD3769ED7A38 /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift-resources-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Copy Pods Resources"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift-resources-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; - BBF5C5D44E878689104526D9 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-FIAMReferenceSwift-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - C45D95F46F4377C48D861896 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-FIAMReferenceSwift/Pods-FIAMReferenceSwift-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - C7965CB691942633E444DB3C /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReference/Pods-FIAMReference-resources-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Copy Pods Resources"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-FIAMReference/Pods-FIAMReference-resources-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-FIAMReference/Pods-FIAMReference-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 3E64A794229376BB003EE93A /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -450,6 +304,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -461,6 +316,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -475,7 +331,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -509,6 +365,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -520,6 +377,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -528,17 +386,17 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; VALIDATE_PRODUCT = YES; }; name = Release; }; 3E64A7AF229376BC003EE93A /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = B20FEECC6333640D763A6374 /* Pods-FIAMReference.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; @@ -555,7 +413,6 @@ }; 3E64A7B0229376BC003EE93A /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 9E2817EDB630021664AEF7F0 /* Pods-FIAMReference.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; @@ -572,7 +429,6 @@ }; 3E64A7C52294513E003EE93A /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8D026225BF1D8381A23B9CDD /* Pods-FIAMReferenceSwift.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; @@ -592,7 +448,6 @@ }; 3E64A7C62294513E003EE93A /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 60DA3A39F9552E8B37AD597C /* Pods-FIAMReferenceSwift.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; @@ -641,6 +496,30 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7951BD2D2C887B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7951BF2D2C8885000FD694 /* FirebaseInAppMessaging-Beta */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951BD2D2C887B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = "FirebaseInAppMessaging-Beta"; + }; + 8D7951C12D2C888E000FD694 /* FirebaseInAppMessaging-Beta */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951BD2D2C887B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = "FirebaseInAppMessaging-Beta"; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 3E64A790229376BB003EE93A /* Project object */; } diff --git a/inappmessaging/FIAMReference/FIAMReference/AppDelegate.m b/inappmessaging/FIAMReference/FIAMReference/AppDelegate.m index 9136a8d2..708c1619 100644 --- a/inappmessaging/FIAMReference/FIAMReference/AppDelegate.m +++ b/inappmessaging/FIAMReference/FIAMReference/AppDelegate.m @@ -16,6 +16,7 @@ #import "AppDelegate.h" +@import FirebaseCore; @import FirebaseInAppMessaging; #import "CardActionFiamDelegate.h" diff --git a/inappmessaging/FIAMReference/FIAMReference/CardActionFiamDelegate.m b/inappmessaging/FIAMReference/FIAMReference/CardActionFiamDelegate.m index 84f59038..7d6a0335 100644 --- a/inappmessaging/FIAMReference/FIAMReference/CardActionFiamDelegate.m +++ b/inappmessaging/FIAMReference/FIAMReference/CardActionFiamDelegate.m @@ -40,12 +40,16 @@ - (void)messageDismissed:(nonnull FIRInAppMessagingDisplayMessage *)inAppMessage @end // [END fiam_card_action_delegate] +@interface ExampleCardActionDelegate: NSObject +@end + // [START fiam_card_action_delegate_bundles] -@implementation CardActionFiamDelegate +@implementation ExampleCardActionDelegate - (void)messageClicked:(nonnull FIRInAppMessagingDisplayMessage *)inAppMessage { - appData = inAppMessage.appData + NSDictionary *appData = inAppMessage.appData; + NSLog(@"Message data: %@", appData); // ... } diff --git a/inappmessaging/FIAMReference/FIAMReferenceSwift/CardActionFiamDelegate.swift b/inappmessaging/FIAMReference/FIAMReferenceSwift/CardActionFiamDelegate.swift index e5262d87..6349e9c6 100644 --- a/inappmessaging/FIAMReference/FIAMReferenceSwift/CardActionFiamDelegate.swift +++ b/inappmessaging/FIAMReference/FIAMReferenceSwift/CardActionFiamDelegate.swift @@ -24,7 +24,7 @@ class CardActionFiamDelegate : NSObject, InAppMessagingDisplayDelegate { } func messageDismissed(_ inAppMessage: InAppMessagingDisplayMessage, - dismissType: FIRInAppMessagingDismissType) { + dismissType: InAppMessagingDismissType) { // ... } @@ -41,7 +41,7 @@ class CardActionFiamDelegate : NSObject, InAppMessagingDisplayDelegate { // [START fiam_card_action_delegate_bundles] -class CardActionFiamDelegate : NSObject, InAppMessagingDisplayDelegate { +class CardActionDelegate : NSObject, InAppMessagingDisplayDelegate { func messageClicked(_ inAppMessage: InAppMessagingDisplayMessage) { // Get data bundle from the inapp message diff --git a/inappmessaging/Podfile b/inappmessaging/Podfile deleted file mode 100644 index 30c17274..00000000 --- a/inappmessaging/Podfile +++ /dev/null @@ -1,14 +0,0 @@ -project 'FIAMReference/FIAMReference.xcodeproj/' - -platform :ios, '8.0' -use_frameworks! - -pod 'Firebase' -pod 'Firebase/InAppMessagingDisplay' - -target 'FIAMReference' do -end - -target 'FIAMReferenceSwift' do - use_frameworks! -end diff --git a/inappmessaging/Podfile.lock b/inappmessaging/Podfile.lock deleted file mode 100644 index 0f8b6bcf..00000000 --- a/inappmessaging/Podfile.lock +++ /dev/null @@ -1,89 +0,0 @@ -PODS: - - Firebase (2.5.1) - - Firebase/CoreOnly (6.15.0): - - FirebaseCore (= 6.6.0) - - Firebase/InAppMessagingDisplay (6.15.0): - - Firebase/CoreOnly - - FirebaseInAppMessagingDisplay (~> 0.15.5) - - FirebaseAnalyticsInterop (1.5.0) - - FirebaseCore (6.6.0): - - FirebaseCoreDiagnostics (~> 1.2) - - FirebaseCoreDiagnosticsInterop (~> 1.2) - - GoogleUtilities/Environment (~> 6.5) - - GoogleUtilities/Logger (~> 6.5) - - FirebaseCoreDiagnostics (1.7.0): - - GoogleDataTransport (~> 7.4) - - GoogleUtilities/Environment (~> 6.7) - - GoogleUtilities/Logger (~> 6.7) - - nanopb (~> 1.30906.0) - - FirebaseCoreDiagnosticsInterop (1.2.0) - - FirebaseInAppMessaging (0.15.3): - - FirebaseAnalyticsInterop (~> 1.3) - - FirebaseCore (~> 6.2) - - FirebaseInstanceID (~> 4.0) - - FirebaseInAppMessagingDisplay (0.15.5): - - FirebaseCore (~> 6.2) - - FirebaseInAppMessaging (>= 0.15.0) - - FirebaseInstallations (1.3.0): - - FirebaseCore (~> 6.6) - - GoogleUtilities/Environment (~> 6.6) - - GoogleUtilities/UserDefaults (~> 6.6) - - PromisesObjC (~> 1.2) - - FirebaseInstanceID (4.3.4): - - FirebaseCore (~> 6.6) - - FirebaseInstallations (~> 1.0) - - GoogleUtilities/Environment (~> 6.5) - - GoogleUtilities/UserDefaults (~> 6.5) - - GoogleDataTransport (7.5.1): - - nanopb (~> 1.30906.0) - - GoogleUtilities/Environment (6.7.2): - - PromisesObjC (~> 1.2) - - GoogleUtilities/Logger (6.7.2): - - GoogleUtilities/Environment - - GoogleUtilities/UserDefaults (6.7.2): - - GoogleUtilities/Logger - - nanopb (1.30906.0): - - nanopb/decode (= 1.30906.0) - - nanopb/encode (= 1.30906.0) - - nanopb/decode (1.30906.0) - - nanopb/encode (1.30906.0) - - PromisesObjC (1.2.10) - -DEPENDENCIES: - - Firebase - - Firebase/InAppMessagingDisplay - -SPEC REPOS: - trunk: - - Firebase - - FirebaseAnalyticsInterop - - FirebaseCore - - FirebaseCoreDiagnostics - - FirebaseCoreDiagnosticsInterop - - FirebaseInAppMessaging - - FirebaseInAppMessagingDisplay - - FirebaseInstallations - - FirebaseInstanceID - - GoogleDataTransport - - GoogleUtilities - - nanopb - - PromisesObjC - -SPEC CHECKSUMS: - Firebase: 5d77105d9740a07ca6b16927ca971db7e860faaf - FirebaseAnalyticsInterop: 3f86269c38ae41f47afeb43ebf32a001f58fcdae - FirebaseCore: 4aeb81ff53dcd9a3634ca725dc1fb8c2a4622046 - FirebaseCoreDiagnostics: 770ac5958e1372ce67959ae4b4f31d8e127c3ac1 - FirebaseCoreDiagnosticsInterop: 296e2c5f5314500a850ad0b83e9e7c10b011a850 - FirebaseInAppMessaging: 5db5fa181ed4215e02ded09f7e4bbcc2ce624a47 - FirebaseInAppMessagingDisplay: 60a65c8277f17675a8a5b92e9a97cd914b45d4ff - FirebaseInstallations: 6f5f680e65dc374397a483c32d1799ba822a395b - FirebaseInstanceID: cef67c4967c7cecb56ea65d8acbb4834825c587b - GoogleDataTransport: f56af7caa4ed338dc8e138a5d7c5973e66440833 - GoogleUtilities: 7f2f5a07f888cdb145101d6042bc4422f57e70b3 - nanopb: 59317e09cf1f1a0af72f12af412d54edf52603fc - PromisesObjC: b14b1c6b68e306650688599de8a45e49fae81151 - -PODFILE CHECKSUM: ee1d0162c4b114166138141943031a3ae6c42221 - -COCOAPODS: 1.11.3 diff --git a/installations/InstallationsSnippets.xcodeproj/project.pbxproj b/installations/InstallationsSnippets.xcodeproj/project.pbxproj index 479cfeb4..c66d3adb 100644 --- a/installations/InstallationsSnippets.xcodeproj/project.pbxproj +++ b/installations/InstallationsSnippets.xcodeproj/project.pbxproj @@ -3,10 +3,11 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ + 8D7951C62D2C8A15000FD694 /* FirebaseInstallations in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951C52D2C8A15000FD694 /* FirebaseInstallations */; }; 8DC74B6624A3DABF004C5F44 /* ObjCSnippets.m in Sources */ = {isa = PBXBuildFile; fileRef = 8DC74B6524A3DABF004C5F44 /* ObjCSnippets.m */; }; 8DF2A72824A3D78300737F46 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DF2A72724A3D78300737F46 /* AppDelegate.swift */; }; 8DF2A72A24A3D78300737F46 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DF2A72924A3D78300737F46 /* SceneDelegate.swift */; }; @@ -49,6 +50,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951C62D2C8A15000FD694 /* FirebaseInstallations in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -62,11 +64,11 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 8AD735E937155091CB79F9CC /* Pods */ = { + 8D7951C42D2C8A15000FD694 /* Frameworks */ = { isa = PBXGroup; children = ( ); - path = Pods; + name = Frameworks; sourceTree = ""; }; 8DF2A71B24A3D78300737F46 = { @@ -74,8 +76,8 @@ children = ( 8DF2A72624A3D78300737F46 /* InstallationsSnippets */, 8DF2A73D24A3D78300737F46 /* InstallationsSnippetsTests */, + 8D7951C42D2C8A15000FD694 /* Frameworks */, 8DF2A72524A3D78300737F46 /* Products */, - 8AD735E937155091CB79F9CC /* Pods */, ); sourceTree = ""; }; @@ -166,8 +168,9 @@ 8DF2A71C24A3D78300737F46 /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 1140; - LastUpgradeCheck = 1140; + LastUpgradeCheck = 1610; ORGANIZATIONNAME = Firebase; TargetAttributes = { 8DF2A72324A3D78300737F46 = { @@ -189,6 +192,9 @@ Base, ); mainGroup = 8DF2A71B24A3D78300737F46; + packageReferences = ( + 8D7951C32D2C89F0000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 8DF2A72524A3D78300737F46 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -287,6 +293,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -297,6 +304,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -347,6 +355,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -357,6 +366,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -421,7 +431,6 @@ 8DF2A74724A3D78300737F46 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = InstallationsSnippetsTests/Info.plist; @@ -442,7 +451,6 @@ 8DF2A74824A3D78300737F46 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = InstallationsSnippetsTests/Info.plist; @@ -491,6 +499,25 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7951C32D2C89F0000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7951C52D2C8A15000FD694 /* FirebaseInstallations */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951C32D2C89F0000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseInstallations; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 8DF2A71C24A3D78300737F46 /* Project object */; } diff --git a/installations/InstallationsSnippets/AppDelegate.swift b/installations/InstallationsSnippets/AppDelegate.swift index d0c604f5..f0d3cd6e 100644 --- a/installations/InstallationsSnippets/AppDelegate.swift +++ b/installations/InstallationsSnippets/AppDelegate.swift @@ -14,6 +14,7 @@ // limitations under the License. // +import UIKit import FirebaseCore import FirebaseInstallations @@ -48,45 +49,43 @@ class AppDelegate: UIResponder, UIApplicationDelegate { queue: nil ) { (notification) in // Fetch new Installation ID - self.fetchInstallationToken() + Task { + await self.fetchInstallationToken() + } } // [END handle_installation_id_change] } - func fetchInstallationID() { + func fetchInstallationID() async { // [START fetch_installation_id] - Installations.installations().installationID { (id, error) in - if let error = error { - print("Error fetching id: \(error)") - return - } - guard let id = id else { return } + do { + let id = try await Installations.installations().installationID() print("Installation ID: \(id)") + } catch { + print("Error fetching id: \(error)") } // [END fetch_installation_id] } - func fetchInstallationToken() { + func fetchInstallationToken() async { // [START fetch_installation_token] - Installations.installations().authTokenForcingRefresh(true, completion: { (result, error) in - if let error = error { - print("Error fetching token: \(error)") - return - } - guard let result = result else { return } + do { + let result = try await Installations.installations() + .authTokenForcingRefresh(true) print("Installation auth token: \(result.authToken)") - }) + } catch { + print("Error fetching token: \(error)") + } // [END fetch_installation_token] } - func deleteInstallation() { + func deleteInstallation() async { // [START delete_installation] - Installations.installations().delete { error in - if let error = error { - print("Error deleting installation: \(error)") - return - } + do { + try await Installations.installations().delete() print("Installation deleted"); + } catch { + print("Error deleting installation: \(error)") } // [END delete_installation] } diff --git a/installations/Podfile b/installations/Podfile deleted file mode 100644 index d3cb87f4..00000000 --- a/installations/Podfile +++ /dev/null @@ -1,15 +0,0 @@ -# Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' - -target 'InstallationsSnippets' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - pod 'FirebaseInstallations' - - target 'InstallationsSnippetsTests' do - inherit! :search_paths - # Pods for testing - end - -end diff --git a/installations/Podfile.lock b/installations/Podfile.lock deleted file mode 100644 index 84ddc05b..00000000 --- a/installations/Podfile.lock +++ /dev/null @@ -1,42 +0,0 @@ -PODS: - - FirebaseCore (10.2.0): - - FirebaseCoreInternal (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/Logger (~> 7.8) - - FirebaseCoreInternal (10.2.0): - - "GoogleUtilities/NSData+zlib (~> 7.8)" - - FirebaseInstallations (10.2.0): - - FirebaseCore (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/UserDefaults (~> 7.8) - - PromisesObjC (~> 2.1) - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GoogleUtilities/UserDefaults (7.10.0): - - GoogleUtilities/Logger - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - FirebaseInstallations - -SPEC REPOS: - trunk: - - FirebaseCore - - FirebaseCoreInternal - - FirebaseInstallations - - GoogleUtilities - - PromisesObjC - -SPEC CHECKSUMS: - FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1 - FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f - FirebaseInstallations: 004915af170935e3a583faefd5f8bc851afc220f - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: 904aacceb39f206bdcc33f354e02d1d3d6343a46 - -COCOAPODS: 1.11.3 diff --git a/invites/Podfile.lock b/invites/Podfile.lock index 6c87fab1..ad0a65e7 100644 --- a/invites/Podfile.lock +++ b/invites/Podfile.lock @@ -147,4 +147,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 642789e1fcae7a05996d36ee829b1b64089587bd -COCOAPODS: 1.11.3 +COCOAPODS: 1.15.2 diff --git a/ml-functions/MLFunctionsExample.xcodeproj/project.pbxproj b/ml-functions/MLFunctionsExample.xcodeproj/project.pbxproj index 5862e9fe..7a47ff3e 100644 --- a/ml-functions/MLFunctionsExample.xcodeproj/project.pbxproj +++ b/ml-functions/MLFunctionsExample.xcodeproj/project.pbxproj @@ -3,10 +3,12 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ + 8D7951CA2D2C8AAA000FD694 /* FirebaseFunctions in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951C92D2C8AAA000FD694 /* FirebaseFunctions */; }; + 8D7951CC2D2C8AB2000FD694 /* FirebaseFunctions in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951CB2D2C8AB2000FD694 /* FirebaseFunctions */; }; 8D8FA34322F4CAB100213E06 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D8FA34222F4CAB100213E06 /* AppDelegate.m */; }; 8D8FA34622F4CAB100213E06 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D8FA34522F4CAB100213E06 /* ViewController.m */; }; 8D8FA34922F4CAB100213E06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D8FA34722F4CAB100213E06 /* Main.storyboard */; }; @@ -45,6 +47,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951CA2D2C8AAA000FD694 /* FirebaseFunctions in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -52,19 +55,27 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951CC2D2C8AB2000FD694 /* FirebaseFunctions in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 8D7951C82D2C8AAA000FD694 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; 8D8FA33522F4CAB100213E06 = { isa = PBXGroup; children = ( 8D8FA34022F4CAB100213E06 /* MLFunctionsExample */, 8D8FA35C22F4CAF700213E06 /* MLFunctionsExampleSwift */, + 8D7951C82D2C8AAA000FD694 /* Frameworks */, 8D8FA33F22F4CAB100213E06 /* Products */, - E21099940C3416ACBB0EB9EC /* Pods */, ); sourceTree = ""; }; @@ -106,13 +117,6 @@ path = MLFunctionsExampleSwift; sourceTree = ""; }; - E21099940C3416ACBB0EB9EC /* Pods */ = { - isa = PBXGroup; - children = ( - ); - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -156,8 +160,9 @@ 8D8FA33622F4CAB100213E06 /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 1020; - LastUpgradeCheck = 1230; + LastUpgradeCheck = 1610; ORGANIZATIONNAME = Firebase; TargetAttributes = { 8D8FA33D22F4CAB100213E06 = { @@ -177,6 +182,9 @@ Base, ); mainGroup = 8D8FA33522F4CAB100213E06; + packageReferences = ( + 8D7951C72D2C8A9B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); productRefGroup = 8D8FA33F22F4CAB100213E06 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -306,6 +314,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -366,6 +375,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -389,6 +399,7 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = MLFunctionsExample/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -405,6 +416,7 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = MLFunctionsExample/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -421,6 +433,7 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = MLFunctionsExampleSwift/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -440,6 +453,7 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = MLFunctionsExampleSwift/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -484,6 +498,30 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7951C72D2C8A9B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7951C92D2C8AAA000FD694 /* FirebaseFunctions */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951C72D2C8A9B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseFunctions; + }; + 8D7951CB2D2C8AB2000FD694 /* FirebaseFunctions */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951C72D2C8A9B000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseFunctions; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 8D8FA33622F4CAB100213E06 /* Project object */; } diff --git a/ml-functions/MLFunctionsExample/ViewController.m b/ml-functions/MLFunctionsExample/ViewController.m index f556313e..2d5b80c9 100644 --- a/ml-functions/MLFunctionsExample/ViewController.m +++ b/ml-functions/MLFunctionsExample/ViewController.m @@ -85,10 +85,10 @@ - (void)annotateImage:(NSDictionary *)requestData { callWithObject:requestData completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) { if (error) { - if (error.domain == FIRFunctionsErrorDomain) { + if ([error.domain isEqualToString:@"com.firebase.functions"]) { FIRFunctionsErrorCode code = error.code; NSString *message = error.localizedDescription; - NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey]; + NSObject *details = error.userInfo[@"details"]; } // ... } diff --git a/ml-functions/MLFunctionsExampleSwift/ViewController.swift b/ml-functions/MLFunctionsExampleSwift/ViewController.swift index 3f41ee45..37204bce 100644 --- a/ml-functions/MLFunctionsExampleSwift/ViewController.swift +++ b/ml-functions/MLFunctionsExampleSwift/ViewController.swift @@ -29,7 +29,7 @@ class ViewController: UIViewController { func prepareData(uiImage: UIImage) { // [START base64encodeImage] - guard let imageData = uiImage.jpegData(compressionQuality: 1.0f) else { return } + guard let imageData = uiImage.jpegData(compressionQuality: 1.0) else { return } let base64encodedImage = imageData.base64EncodedString() // [END base64encodeImage] } @@ -71,9 +71,12 @@ class ViewController: UIViewController { // [END prepareLandmarkData] } - func annotateImage(requestData: Dictionary) { + func annotateImage(requestData: Any) async { // [START function_annotateImage] - functions.httpsCallable("annotateImage").call(requestData) { (result, error) in + do { + let result = try await functions.httpsCallable("annotateImage").call(requestData) + print(result) + } catch { if let error = error as NSError? { if error.domain == FunctionsErrorDomain { let code = FunctionsErrorCode(rawValue: error.code) @@ -82,7 +85,6 @@ class ViewController: UIViewController { } // ... } - // Function completed succesfully } // [END function_annotateImage] } @@ -101,46 +103,51 @@ class ViewController: UIViewController { func getRecognizedTextsFrom(_ result: HTTPSCallableResult?) { // [START function_getRecognizedTexts] - guard let annotation = (result?.data as? [String: Any])?["fullTextAnnotation"] as? [String: Any] else { return } - print("%nComplete annotation:") - let text = annotation["text"] as? String ?? "" - print("%n\(text)") + let annotation = result.flatMap { $0.data as? [String: Any] } + .flatMap { $0["fullTextAnnotation"] } + .flatMap { $0 as? [String: Any] } + guard let annotation = annotation else { return } + + if let text = annotation["text"] as? String { + print("Complete annotation: \(text)") + } // [END function_getRecognizedTexts] -   + // [START function_getRecognizedTexts_details] guard let pages = annotation["pages"] as? [[String: Any]] else { return } for page in pages { - var pageText = "" - guard let blocks = page["blocks"] as? [[String: Any]] else { continue } - for block in blocks { + var pageText = "" + guard let blocks = page["blocks"] as? [[String: Any]] else { continue } + for block in blocks { var blockText = "" guard let paragraphs = block["paragraphs"] as? [[String: Any]] else { continue } for paragraph in paragraphs { - var paragraphText = "" - guard let words = paragraph["words"] as? [[String: Any]] else { continue } - for word in words { + var paragraphText = "" + guard let words = paragraph["words"] as? [[String: Any]] else { continue } + for word in words { var wordText = "" guard let symbols = word["symbols"] as? [[String: Any]] else { continue } for symbol in symbols { - let text = symbol["text"] as? String ?? "" - let confidence = symbol["confidence"] as? Float ?? 0.0 - wordText += text - print("Symbol text: \(text) (confidence: \(confidence)%n") + let text = symbol["text"] as? String ?? "" + let confidence = symbol["confidence"] as? Float ?? 0.0 + wordText += text + print("Symbol text: \(text) (confidence: \(confidence)%n") } let confidence = word["confidence"] as? Float ?? 0.0 print("Word text: \(wordText) (confidence: \(confidence)%n%n") let boundingBox = word["boundingBox"] as? [Float] ?? [0.0, 0.0, 0.0, 0.0] print("Word bounding box: \(boundingBox.description)%n") paragraphText += wordText - } - print("%nParagraph: %n\(paragraphText)%n") - let boundingBox = paragraph["boundingBox"] as? [Float] ?? [0.0, 0.0, 0.0, 0.0] - print("Paragraph bounding box: \(boundingBox)%n") - let confidence = paragraph["confidence"] as? Float ?? 0.0 - print("Paragraph Confidence: \(confidence)%n") - blockText += paragraphText + } + print("%nParagraph: %n\(paragraphText)%n") + let boundingBox = paragraph["boundingBox"] as? [Float] ?? [0.0, 0.0, 0.0, 0.0] + print("Paragraph bounding box: \(boundingBox)%n") + let confidence = paragraph["confidence"] as? Float ?? 0.0 + print("Paragraph Confidence: \(confidence)%n") + blockText += paragraphText } pageText += blockText + } } // [END function_getRecognizedTexts_details] } diff --git a/ml-functions/Podfile b/ml-functions/Podfile deleted file mode 100644 index c0a3e167..00000000 --- a/ml-functions/Podfile +++ /dev/null @@ -1,18 +0,0 @@ -# Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' - -target 'MLFunctionsExample' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - pod 'Firebase/Functions' - -end - -target 'MLFunctionsExampleSwift' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - pod 'Firebase/Functions' - -end diff --git a/ml-functions/Podfile.lock b/ml-functions/Podfile.lock deleted file mode 100644 index c4f2730a..00000000 --- a/ml-functions/Podfile.lock +++ /dev/null @@ -1,69 +0,0 @@ -PODS: - - Firebase/CoreOnly (10.2.0): - - FirebaseCore (= 10.2.0) - - Firebase/Functions (10.2.0): - - Firebase/CoreOnly - - FirebaseFunctions (~> 10.2.0) - - FirebaseAppCheckInterop (10.2.0) - - FirebaseAuthInterop (10.2.0) - - FirebaseCore (10.2.0): - - FirebaseCoreInternal (~> 10.0) - - GoogleUtilities/Environment (~> 7.8) - - GoogleUtilities/Logger (~> 7.8) - - FirebaseCoreExtension (10.2.0): - - FirebaseCore (~> 10.0) - - FirebaseCoreInternal (10.2.0): - - "GoogleUtilities/NSData+zlib (~> 7.8)" - - FirebaseFunctions (10.2.0): - - FirebaseAppCheckInterop (~> 10.0) - - FirebaseAuthInterop (~> 10.0) - - FirebaseCore (~> 10.0) - - FirebaseCoreExtension (~> 10.0) - - FirebaseMessagingInterop (~> 10.0) - - FirebaseSharedSwift (~> 10.0) - - GTMSessionFetcher/Core (< 4.0, >= 2.1) - - FirebaseMessagingInterop (10.2.0) - - FirebaseSharedSwift (10.2.0) - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GTMSessionFetcher/Core (3.0.0) - - PromisesObjC (2.1.1) - -DEPENDENCIES: - - Firebase/Functions - -SPEC REPOS: - trunk: - - Firebase - - FirebaseAppCheckInterop - - FirebaseAuthInterop - - FirebaseCore - - FirebaseCoreExtension - - FirebaseCoreInternal - - FirebaseFunctions - - FirebaseMessagingInterop - - FirebaseSharedSwift - - GoogleUtilities - - GTMSessionFetcher - - PromisesObjC - -SPEC CHECKSUMS: - Firebase: a3ea7eba4382afd83808376edb99acdaff078dcf - FirebaseAppCheckInterop: af164d9c623f82174e3ffa54394dee189587c601 - FirebaseAuthInterop: 027d42ca8fec84dc6151566479af05095a0bd5c0 - FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1 - FirebaseCoreExtension: d08b424832917cf13612021574399afbbedffeef - FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f - FirebaseFunctions: eaa208f64f2f179f0ab9b775fecdec07fdd74d90 - FirebaseMessagingInterop: b46e7fcf39c0e9b16841e258645a320a154af240 - FirebaseSharedSwift: a160b39d4ce77be922b3d6ff009099c7294e36e5 - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - GTMSessionFetcher: c1edebe64e9fb4e8f6415d018edf1fd3eac074a1 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - -PODFILE CHECKSUM: aa543baa476adf0a1eb62d4970ac2cffc30a1931 - -COCOAPODS: 1.11.3 diff --git a/mlkit/Podfile.lock b/mlkit/Podfile.lock index 47e4a1d3..55f2c6d8 100644 --- a/mlkit/Podfile.lock +++ b/mlkit/Podfile.lock @@ -81,7 +81,7 @@ PODS: - nanopb/decode (1.30906.0) - nanopb/encode (1.30906.0) - PromisesObjC (1.2.12) - - Protobuf (3.21.4) + - Protobuf (3.26.1) - TensorFlowLiteC (2.1.0) - TensorFlowLiteObjC (2.1.0): - TensorFlowLiteC (= 2.1.0) @@ -125,10 +125,10 @@ SPEC CHECKSUMS: GTMSessionFetcher: 5595ec75acf5be50814f81e9189490412bad82ba nanopb: 59317e09cf1f1a0af72f12af412d54edf52603fc PromisesObjC: 3113f7f76903778cf4a0586bd1ab89329a0b7b97 - Protobuf: 85a48c73d708782e2869564c0438e211aae98e7a + Protobuf: a53f5173a603075b3522a5c50be63a67a5f3353a TensorFlowLiteC: 215603d4426d93810eace5947e317389554a4b66 TensorFlowLiteObjC: 2e074eb41084037aeda9a8babe111fdd3ac99974 PODFILE CHECKSUM: 4b071879fc5f9391b9325777ac56ce58e70e8b8d -COCOAPODS: 1.11.3 +COCOAPODS: 1.15.2 diff --git a/storage/Podfile b/storage/Podfile index 0d21be70..c54ab2e5 100644 --- a/storage/Podfile +++ b/storage/Podfile @@ -1,3 +1,4 @@ +# Podfile left around for legacy snippets. The project has since been migrated to SPM. platform :ios, '12.0' use_frameworks! diff --git a/storage/Podfile.lock b/storage/Podfile.lock deleted file mode 100644 index 2da3400a..00000000 --- a/storage/Podfile.lock +++ /dev/null @@ -1,91 +0,0 @@ -PODS: - - FirebaseAppCheckInterop (9.6.0) - - FirebaseAuthInterop (9.6.0) - - FirebaseCore (9.6.0): - - FirebaseCoreDiagnostics (~> 9.0) - - FirebaseCoreInternal (~> 9.0) - - GoogleUtilities/Environment (~> 7.7) - - GoogleUtilities/Logger (~> 7.7) - - FirebaseCoreDiagnostics (9.6.0): - - GoogleDataTransport (< 10.0.0, >= 9.1.4) - - GoogleUtilities/Environment (~> 7.7) - - GoogleUtilities/Logger (~> 7.7) - - nanopb (< 2.30910.0, >= 2.30908.0) - - FirebaseCoreExtension (9.6.0): - - FirebaseCore (~> 9.0) - - FirebaseCoreInternal (9.6.0): - - "GoogleUtilities/NSData+zlib (~> 7.7)" - - FirebaseStorage (9.6.0): - - FirebaseAppCheckInterop (~> 9.0) - - FirebaseAuthInterop (~> 9.0) - - FirebaseCore (~> 9.0) - - FirebaseCoreExtension (~> 9.0) - - FirebaseStorageInternal (~> 9.0) - - FirebaseStorageInternal (9.6.0): - - FirebaseCore (~> 9.0) - - GTMSessionFetcher/Core (< 3.0, >= 1.7) - - FirebaseStorageUI (12.3.0): - - FirebaseStorage (< 11.0, >= 8.0) - - SDWebImage (~> 5.6) - - GoogleDataTransport (9.2.0): - - GoogleUtilities/Environment (~> 7.7) - - nanopb (< 2.30910.0, >= 2.30908.0) - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Environment (7.10.0): - - PromisesObjC (< 3.0, >= 1.2) - - GoogleUtilities/Logger (7.10.0): - - GoogleUtilities/Environment - - "GoogleUtilities/NSData+zlib (7.10.0)" - - GTMSessionFetcher/Core (2.3.0) - - nanopb (2.30909.0): - - nanopb/decode (= 2.30909.0) - - nanopb/encode (= 2.30909.0) - - nanopb/decode (2.30909.0) - - nanopb/encode (2.30909.0) - - PromisesObjC (2.1.1) - - SDWebImage (5.14.2): - - SDWebImage/Core (= 5.14.2) - - SDWebImage/Core (5.14.2) - -DEPENDENCIES: - - FirebaseStorage (~> 9.0) - - FirebaseStorageUI - -SPEC REPOS: - trunk: - - FirebaseAppCheckInterop - - FirebaseAuthInterop - - FirebaseCore - - FirebaseCoreDiagnostics - - FirebaseCoreExtension - - FirebaseCoreInternal - - FirebaseStorage - - FirebaseStorageInternal - - FirebaseStorageUI - - GoogleDataTransport - - GoogleUtilities - - GTMSessionFetcher - - nanopb - - PromisesObjC - - SDWebImage - -SPEC CHECKSUMS: - FirebaseAppCheckInterop: d5ecda0c09f8069406643d6e0fa12c09d1b736e3 - FirebaseAuthInterop: b6cf02117f13a8400c8c8b4421e12c6e850bcaf3 - FirebaseCore: 2082fffcd855f95f883c0a1641133eb9bbe76d40 - FirebaseCoreDiagnostics: 99a495094b10a57eeb3ae8efa1665700ad0bdaa6 - FirebaseCoreExtension: e83465d1236b166d1d445bbf0e82b65acb30b73b - FirebaseCoreInternal: bca76517fe1ed381e989f5e7d8abb0da8d85bed3 - FirebaseStorage: 1fead543a1f441c3b434c1c9f12560dd82f8b568 - FirebaseStorageInternal: 81d8a597324ccd06c41a43c5700bc1185a2fc328 - FirebaseStorageUI: e395358d689cd64b967b2402939ee0f503de63b5 - GoogleDataTransport: 1c8145da7117bd68bbbed00cf304edb6a24de00f - GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95 - GTMSessionFetcher: 3a63d75eecd6aa32c2fc79f578064e1214dfdec2 - nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431 - PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb - SDWebImage: b9a731e1d6307f44ca703b3976d18c24ca561e84 - -PODFILE CHECKSUM: 391f1ea32d2ab69e86fbbcaed454945eef4950b4 - -COCOAPODS: 1.11.3 diff --git a/storage/StorageReference.xcodeproj/project.pbxproj b/storage/StorageReference.xcodeproj/project.pbxproj index 312025d3..999509a5 100644 --- a/storage/StorageReference.xcodeproj/project.pbxproj +++ b/storage/StorageReference.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -15,6 +15,10 @@ 8D64553B1DFF56CE00972DCE /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D6455391DFF56CE00972DCE /* Main.storyboard */; }; 8D64553D1DFF56CE00972DCE /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8D64553C1DFF56CE00972DCE /* Assets.xcassets */; }; 8D6455401DFF56CE00972DCE /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8D64553E1DFF56CE00972DCE /* LaunchScreen.storyboard */; }; + 8D7951D02D2C8C71000FD694 /* FirebaseStorage in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951CF2D2C8C71000FD694 /* FirebaseStorage */; }; + 8D7951D22D2C8C77000FD694 /* FirebaseStorage in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951D12D2C8C77000FD694 /* FirebaseStorage */; }; + 8D7951D52D2C8D2A000FD694 /* FirebaseStorageUI in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951D42D2C8D2A000FD694 /* FirebaseStorageUI */; }; + 8D7951D72D2C8D33000FD694 /* FirebaseStorageUI in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7951D62D2C8D33000FD694 /* FirebaseStorageUI */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -38,6 +42,8 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951D22D2C8C77000FD694 /* FirebaseStorage in Frameworks */, + 8D7951D52D2C8D2A000FD694 /* FirebaseStorageUI in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -45,19 +51,14 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8D7951D02D2C8C71000FD694 /* FirebaseStorage in Frameworks */, + 8D7951D72D2C8D33000FD694 /* FirebaseStorageUI in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 0B3979B2C8769728EE24D424 /* Pods */ = { - isa = PBXGroup; - children = ( - ); - path = Pods; - sourceTree = ""; - }; 1090B0671EBCE02000A8F759 /* StorageReferenceSwift */ = { isa = PBXGroup; children = ( @@ -72,8 +73,8 @@ children = ( 8D64552F1DFF56CE00972DCE /* StorageReference */, 1090B0671EBCE02000A8F759 /* StorageReferenceSwift */, + 8D7951CE2D2C8C71000FD694 /* Frameworks */, 8D64552E1DFF56CE00972DCE /* Products */, - 0B3979B2C8769728EE24D424 /* Pods */, ); sourceTree = ""; }; @@ -110,6 +111,13 @@ name = "Supporting Files"; sourceTree = ""; }; + 8D7951CE2D2C8C71000FD694 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -153,8 +161,9 @@ 8D6455251DFF56CD00972DCE /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 0830; - LastUpgradeCheck = 0830; + LastUpgradeCheck = 1610; ORGANIZATIONNAME = "Google Inc."; TargetAttributes = { 1090B0651EBCE02000A8F759 = { @@ -170,14 +179,17 @@ }; buildConfigurationList = 8D6455281DFF56CD00972DCE /* Build configuration list for PBXProject "StorageReference" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( - English, en, Base, ); mainGroup = 8D6455241DFF56CD00972DCE; + packageReferences = ( + 8D7951CD2D2C8C62000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + 8D7951D32D2C8D15000FD694 /* XCRemoteSwiftPackageReference "FirebaseUI-iOS" */, + ); productRefGroup = 8D64552E1DFF56CE00972DCE /* Products */; projectDirPath = ""; projectRoot = ""; @@ -258,13 +270,17 @@ CLANG_ENABLE_MODULES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; INFOPLIST_FILE = "$(SRCROOT)/StorageReference/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 10.3; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + OTHER_SWIFT_FLAGS = "-Xcc -fmodule-map-file=$(GENERATED_MODULEMAP_DIR)/FirebaseStorage.modulemap"; PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.referencecode.FirebaseStorageReference; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; }; name = Debug; }; @@ -276,12 +292,17 @@ CLANG_ENABLE_MODULES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; INFOPLIST_FILE = "$(SRCROOT)/StorageReference/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 10.3; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + OTHER_SWIFT_FLAGS = "-Xcc -fmodule-map-file=$(GENERATED_MODULEMAP_DIR)/FirebaseStorage.modulemap"; PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.referencecode.FirebaseStorageReference; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 5.0; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 6.0; }; name = Release; }; @@ -289,20 +310,30 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_SUSPICIOUS_MOVES = YES; CLANG_WARN_UNREACHABLE_CODE = YES; @@ -312,6 +343,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -326,10 +358,11 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.1; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; + SWIFT_VERSION = 6.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; @@ -338,20 +371,30 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_SUSPICIOUS_MOVES = YES; CLANG_WARN_UNREACHABLE_CODE = YES; @@ -361,6 +404,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -369,10 +413,12 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.1; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 6.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -383,7 +429,11 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = "$(SRCROOT)/StorageReference/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.referencecode.StorageReference; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -394,7 +444,11 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = "$(SRCROOT)/StorageReference/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.google.firebase.referencecode.StorageReference; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -431,6 +485,48 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D7951CD2D2C8C62000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 11.6.0; + }; + }; + 8D7951D32D2C8D15000FD694 /* XCRemoteSwiftPackageReference "FirebaseUI-iOS" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/FirebaseUI-iOS"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 15.0.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D7951CF2D2C8C71000FD694 /* FirebaseStorage */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951CD2D2C8C62000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseStorage; + }; + 8D7951D12D2C8C77000FD694 /* FirebaseStorage */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951CD2D2C8C62000FD694 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseStorage; + }; + 8D7951D42D2C8D2A000FD694 /* FirebaseStorageUI */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951D32D2C8D15000FD694 /* XCRemoteSwiftPackageReference "FirebaseUI-iOS" */; + productName = FirebaseStorageUI; + }; + 8D7951D62D2C8D33000FD694 /* FirebaseStorageUI */ = { + isa = XCSwiftPackageProductDependency; + package = 8D7951D32D2C8D15000FD694 /* XCRemoteSwiftPackageReference "FirebaseUI-iOS" */; + productName = FirebaseStorageUI; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 8D6455251DFF56CD00972DCE /* Project object */; } diff --git a/storage/StorageReference/ViewController.m b/storage/StorageReference/ViewController.m index 0556d095..30aef157 100644 --- a/storage/StorageReference/ViewController.m +++ b/storage/StorageReference/ViewController.m @@ -244,10 +244,10 @@ - (void)storagePauseExample { // [START firstorage_progress] // Add a progress observer to an upload task - FIRStorageHandle observer = [uploadTask observeStatus:FIRStorageTaskStatusProgress - handler:^(FIRStorageTaskSnapshot *snapshot) { - // A progress event occurred - }]; + NSString *observer = [uploadTask observeStatus:FIRStorageTaskStatusProgress + handler:^(FIRStorageTaskSnapshot *snapshot) { + // A progress event occurred + }]; // [END firstorage_progress] } @@ -259,10 +259,10 @@ - (void)storageTaskExample { // [START firstorage_task] // Create a task listener handle - FIRStorageHandle observer = [uploadTask observeStatus:FIRStorageTaskStatusProgress - handler:^(FIRStorageTaskSnapshot *snapshot) { - // A progress event occurred - }]; + NSString *observer = [uploadTask observeStatus:FIRStorageTaskStatusProgress + handler:^(FIRStorageTaskSnapshot *snapshot) { + // A progress event occurred + }]; // Remove an individual observer [uploadTask removeObserverWithHandle:observer]; @@ -446,10 +446,10 @@ - (void)storageDownloadPauseExample { // [START firstorage_download_observe] // Add a progress observer to a download task - FIRStorageHandle observer = [downloadTask observeStatus:FIRStorageTaskStatusProgress - handler:^(FIRStorageTaskSnapshot *snapshot) { - // A progress event occurred - }]; + NSString *observer = [downloadTask observeStatus:FIRStorageTaskStatusProgress + handler:^(FIRStorageTaskSnapshot *snapshot) { + // A progress event occurred + }]; // [END firstorage_download_observe] } @@ -460,10 +460,10 @@ - (void)storageHandleObserverExample { // [START firstorage_handle_observer] // Create a task listener handle - FIRStorageHandle observer = [downloadTask observeStatus:FIRStorageTaskStatusProgress - handler:^(FIRStorageTaskSnapshot *snapshot) { - // A progress event occurred - }]; + NSString *observer = [downloadTask observeStatus:FIRStorageTaskStatusProgress + handler:^(FIRStorageTaskSnapshot *snapshot) { + // A progress event occurred + }]; // Remove an individual observer [downloadTask removeObserverWithHandle:observer]; diff --git a/storage/StorageReferenceSwift/AppDelegate.swift b/storage/StorageReferenceSwift/AppDelegate.swift index 79d8d6fe..7cf52e57 100644 --- a/storage/StorageReferenceSwift/AppDelegate.swift +++ b/storage/StorageReferenceSwift/AppDelegate.swift @@ -24,7 +24,7 @@ import FirebaseCore // ... // [END import_firebase] -@UIApplicationMain +@main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? diff --git a/storage/StorageReferenceSwift/ViewController.swift b/storage/StorageReferenceSwift/ViewController.swift index 5a21b532..5cf1ac24 100644 --- a/storage/StorageReferenceSwift/ViewController.swift +++ b/storage/StorageReferenceSwift/ViewController.swift @@ -16,9 +16,13 @@ import UIKit +import FirebaseCore import FirebaseStorage import FirebaseStorageUI +extension StorageMetadata: @unchecked @retroactive Sendable {} +extension StorageListResult: @unchecked @retroactive Sendable {} + class ViewController: UIViewController { var imageView: UIImageView! @@ -137,7 +141,7 @@ class ViewController: UIViewController { // [END firstorage_upload] } - func storageInMemoryExample() { + func storageInMemoryExample() async { let storageRef = Storage.storage().reference() // [START firstorage_memory] @@ -529,7 +533,7 @@ class ViewController: UIViewController { // [END firstorage_download_combined] } - func storageGetMetadataExample() { + func storageGetMetadataExample() async { let storageRef = Storage.storage().reference() // [START firstorage_get_metadata] @@ -537,17 +541,15 @@ class ViewController: UIViewController { let forestRef = storageRef.child("images/forest.jpg") // Get metadata properties - forestRef.getMetadata { metadata, error in - if let error = error { - // Uh-oh, an error occurred! - } else { - // Metadata now contains the metadata for 'images/forest.jpg' - } + do { + let metadata = try await forestRef.getMetadata() + } catch { + // ... } // [END firstorage_get_metadata] } - func storageChangeMetadataExample() { + func storageChangeMetadataExample() async { let storageRef = Storage.storage().reference() // [START firstorage_change_metadata] @@ -560,17 +562,15 @@ class ViewController: UIViewController { newMetadata.contentType = "image/jpeg" // Update metadata properties - forestRef.updateMetadata(newMetadata) { metadata, error in - if let error = error { - // Uh-oh, an error occurred! - } else { - // Updated metadata for 'images/forest.jpg' is returned - } + do { + let updatedMetadata = try await forestRef.updateMetadata(newMetadata) + } catch { + // ... } // [END firstorage_change_metadata] } - func storageDeleteMetadataExample() { + func storageDeleteMetadataExample() async { let storageRef = Storage.storage().reference() let forestRef = storageRef.child("images/forest.jpg") @@ -578,13 +578,11 @@ class ViewController: UIViewController { let newMetadata = StorageMetadata() newMetadata.contentType = nil - // Delete the metadata property - forestRef.updateMetadata(newMetadata) { metadata, error in - if let error = error { - // Uh-oh, an error occurred! - } else { - // metadata.contentType should be nil - } + do { + // Delete the metadata property + let updatedMetadata = try await forestRef.updateMetadata(newMetadata) + } catch { + // ... } // [END firstorage_delete_metadata] } @@ -600,32 +598,28 @@ class ViewController: UIViewController { // [END firstorage_custom_metadata] } - func storageDeleteFileExample() { + func storageDeleteFileExample() async { let storageRef = Storage.storage().reference() // [START firstorage_delete] // Create a reference to the file to delete let desertRef = storageRef.child("desert.jpg") - // Delete the file - desertRef.delete { error in - if let error = error { - // Uh-oh, an error occurred! - } else { - // File deleted successfully - } + do { + // Delete the file + try await desertRef.delete() + } catch { + // ... } // [END firstorage_delete] } - func listAllFiles() { + func listAllFiles() async { let storage = Storage.storage() // [START storage_list_all] let storageReference = storage.reference().child("files/uid") - storageReference.listAll { (result, error) in - if let error = error { - // ... - } + do { + let result = try await storageReference.listAll() for prefix in result.prefixes { // The prefixes under storageReference. // You may call listAll(completion:) recursively on them. @@ -633,42 +627,38 @@ class ViewController: UIViewController { for item in result.items { // The items under storageReference. } + } catch { + // ... } // [END storage_list_all] } // [START storage_list_paginated] - func listAllPaginated(pageToken: String? = nil) { + func listAllPaginated(pageToken: String? = nil) async throws { let storage = Storage.storage() let storageReference = storage.reference().child("files/uid") - let pageHandler: (StorageListResult, Error?) -> Void = { (result, error) in - if let error = error { - // ... - } - let prefixes = result.prefixes - let items = result.items - - // ... - - // Process next page - if let token = result.pageToken { - self.listAllPaginated(pageToken: token) - } - } - + let listResult: StorageListResult if let pageToken = pageToken { - storageReference.list(withMaxResults: 100, pageToken: pageToken, completion: pageHandler) + listResult = try await storageReference.list(maxResults: 100, pageToken: pageToken) } else { - storageReference.list(withMaxResults: 100, completion: pageHandler) + listResult = try await storageReference.list(maxResults: 100) + } + let prefixes = listResult.prefixes + let items = listResult.items + // Handle list result + // ... + + // Process next page + if let token = listResult.pageToken { + try await listAllPaginated(pageToken: token) } } // [END storage_list_paginated] func emulatorSettings() { // [START storage_emulator_connect] - Storage.storage().useEmulator(withHost:"localhost", port:9199) + Storage.storage().useEmulator(withHost: "127.0.0.1", port: 9199) // [END storage_emulator_connect] - } } diff --git a/vertexai/VertexAISnippets.xcodeproj/project.pbxproj b/vertexai/VertexAISnippets.xcodeproj/project.pbxproj new file mode 100644 index 00000000..70883f14 --- /dev/null +++ b/vertexai/VertexAISnippets.xcodeproj/project.pbxproj @@ -0,0 +1,419 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 8D40F40E2BD1CDC30020872A /* VertexAISnippetsApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D40F40D2BD1CDC30020872A /* VertexAISnippetsApp.swift */; }; + 8D40F4102BD1CDC30020872A /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D40F40F2BD1CDC30020872A /* ContentView.swift */; }; + 8D40F4122BD1CDC40020872A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8D40F4112BD1CDC40020872A /* Assets.xcassets */; }; + 8D40F4162BD1CDC40020872A /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8D40F4152BD1CDC40020872A /* Preview Assets.xcassets */; }; + 8D40F4262BD1CE1A0020872A /* FirebaseAppCheck in Frameworks */ = {isa = PBXBuildFile; productRef = 8D40F4252BD1CE1A0020872A /* FirebaseAppCheck */; }; + 8D40F43D2BD1CE910020872A /* VertexAISnippets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D40F43C2BD1CE910020872A /* VertexAISnippets.swift */; }; + 8D7B83012CD4127C0024A604 /* FirebaseAuth in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7B83002CD4127C0024A604 /* FirebaseAuth */; }; + 8D7B83032CD4127C0024A604 /* FirebaseVertexAI in Frameworks */ = {isa = PBXBuildFile; productRef = 8D7B83022CD4127C0024A604 /* FirebaseVertexAI */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 8D40F40A2BD1CDC30020872A /* VertexAISnippets.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = VertexAISnippets.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 8D40F40D2BD1CDC30020872A /* VertexAISnippetsApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VertexAISnippetsApp.swift; sourceTree = ""; }; + 8D40F40F2BD1CDC30020872A /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + 8D40F4112BD1CDC40020872A /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 8D40F4132BD1CDC40020872A /* VertexAISnippets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = VertexAISnippets.entitlements; sourceTree = ""; }; + 8D40F4152BD1CDC40020872A /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; + 8D40F43C2BD1CE910020872A /* VertexAISnippets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VertexAISnippets.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 8D40F4072BD1CDC30020872A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8D7B83032CD4127C0024A604 /* FirebaseVertexAI in Frameworks */, + 8D7B83012CD4127C0024A604 /* FirebaseAuth in Frameworks */, + 8D40F4262BD1CE1A0020872A /* FirebaseAppCheck in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 8D40F4012BD1CDC30020872A = { + isa = PBXGroup; + children = ( + 8D40F40C2BD1CDC30020872A /* VertexAISnippets */, + 8D40F40B2BD1CDC30020872A /* Products */, + 8D40F4392BD1CE3E0020872A /* Frameworks */, + ); + sourceTree = ""; + }; + 8D40F40B2BD1CDC30020872A /* Products */ = { + isa = PBXGroup; + children = ( + 8D40F40A2BD1CDC30020872A /* VertexAISnippets.app */, + ); + name = Products; + sourceTree = ""; + }; + 8D40F40C2BD1CDC30020872A /* VertexAISnippets */ = { + isa = PBXGroup; + children = ( + 8D40F40D2BD1CDC30020872A /* VertexAISnippetsApp.swift */, + 8D40F43C2BD1CE910020872A /* VertexAISnippets.swift */, + 8D40F40F2BD1CDC30020872A /* ContentView.swift */, + 8D40F4112BD1CDC40020872A /* Assets.xcassets */, + 8D40F4132BD1CDC40020872A /* VertexAISnippets.entitlements */, + 8D40F4142BD1CDC40020872A /* Preview Content */, + ); + path = VertexAISnippets; + sourceTree = ""; + }; + 8D40F4142BD1CDC40020872A /* Preview Content */ = { + isa = PBXGroup; + children = ( + 8D40F4152BD1CDC40020872A /* Preview Assets.xcassets */, + ); + path = "Preview Content"; + sourceTree = ""; + }; + 8D40F4392BD1CE3E0020872A /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 8D40F4092BD1CDC30020872A /* VertexAISnippets */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8D40F4192BD1CDC40020872A /* Build configuration list for PBXNativeTarget "VertexAISnippets" */; + buildPhases = ( + 8D40F4062BD1CDC30020872A /* Sources */, + 8D40F4072BD1CDC30020872A /* Frameworks */, + 8D40F4082BD1CDC30020872A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = VertexAISnippets; + packageProductDependencies = ( + 8D40F4252BD1CE1A0020872A /* FirebaseAppCheck */, + 8D7B83002CD4127C0024A604 /* FirebaseAuth */, + 8D7B83022CD4127C0024A604 /* FirebaseVertexAI */, + ); + productName = VertexAISnippets; + productReference = 8D40F40A2BD1CDC30020872A /* VertexAISnippets.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 8D40F4022BD1CDC30020872A /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1520; + LastUpgradeCheck = 1530; + TargetAttributes = { + 8D40F4092BD1CDC30020872A = { + CreatedOnToolsVersion = 15.2; + }; + }; + }; + buildConfigurationList = 8D40F4052BD1CDC30020872A /* Build configuration list for PBXProject "VertexAISnippets" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 8D40F4012BD1CDC30020872A; + packageReferences = ( + 8D40F41C2BD1CE1A0020872A /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, + ); + productRefGroup = 8D40F40B2BD1CDC30020872A /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 8D40F4092BD1CDC30020872A /* VertexAISnippets */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 8D40F4082BD1CDC30020872A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8D40F4162BD1CDC40020872A /* Preview Assets.xcassets in Resources */, + 8D40F4122BD1CDC40020872A /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 8D40F4062BD1CDC30020872A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8D40F4102BD1CDC30020872A /* ContentView.swift in Sources */, + 8D40F43D2BD1CE910020872A /* VertexAISnippets.swift in Sources */, + 8D40F40E2BD1CDC30020872A /* VertexAISnippetsApp.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 8D40F4172BD1CDC40020872A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 8D40F4182BD1CDC40020872A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SWIFT_COMPILATION_MODE = wholemodule; + }; + name = Release; + }; + 8D40F41A2BD1CDC40020872A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = VertexAISnippets/VertexAISnippets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_ASSET_PATHS = "\"VertexAISnippets/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + IPHONEOS_DEPLOYMENT_TARGET = 17.2; + LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; + "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 14.2; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.firebase.VertexAISnippets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = auto; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 8D40F41B2BD1CDC40020872A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = VertexAISnippets/VertexAISnippets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_ASSET_PATHS = "\"VertexAISnippets/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES; + "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault; + "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + IPHONEOS_DEPLOYMENT_TARGET = 17.2; + LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; + "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 14.2; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.firebase.VertexAISnippets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = auto; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 8D40F4052BD1CDC30020872A /* Build configuration list for PBXProject "VertexAISnippets" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8D40F4172BD1CDC40020872A /* Debug */, + 8D40F4182BD1CDC40020872A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8D40F4192BD1CDC40020872A /* Build configuration list for PBXNativeTarget "VertexAISnippets" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8D40F41A2BD1CDC40020872A /* Debug */, + 8D40F41B2BD1CDC40020872A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 8D40F41C2BD1CE1A0020872A /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk"; + requirement = { + branch = main; + kind = branch; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 8D40F4252BD1CE1A0020872A /* FirebaseAppCheck */ = { + isa = XCSwiftPackageProductDependency; + package = 8D40F41C2BD1CE1A0020872A /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAppCheck; + }; + 8D7B83002CD4127C0024A604 /* FirebaseAuth */ = { + isa = XCSwiftPackageProductDependency; + package = 8D40F41C2BD1CE1A0020872A /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAuth; + }; + 8D7B83022CD4127C0024A604 /* FirebaseVertexAI */ = { + isa = XCSwiftPackageProductDependency; + package = 8D40F41C2BD1CE1A0020872A /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseVertexAI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 8D40F4022BD1CDC30020872A /* Project object */; +} diff --git a/vertexai/VertexAISnippets/Assets.xcassets/AccentColor.colorset/Contents.json b/vertexai/VertexAISnippets/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/vertexai/VertexAISnippets/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/vertexai/VertexAISnippets/Assets.xcassets/AppIcon.appiconset/Contents.json b/vertexai/VertexAISnippets/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..532cd729 --- /dev/null +++ b/vertexai/VertexAISnippets/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,63 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "512x512" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "512x512" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/vertexai/VertexAISnippets/Assets.xcassets/Contents.json b/vertexai/VertexAISnippets/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/vertexai/VertexAISnippets/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/vertexai/VertexAISnippets/ContentView.swift b/vertexai/VertexAISnippets/ContentView.swift new file mode 100644 index 00000000..0c5e96f7 --- /dev/null +++ b/vertexai/VertexAISnippets/ContentView.swift @@ -0,0 +1,31 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftUI + +struct ContentView: View { + var body: some View { + VStack { + Image(systemName: "globe") + .imageScale(.large) + .foregroundStyle(.tint) + Text("Hello, world!") + } + .padding() + } +} + +#Preview { + ContentView() +} diff --git a/vertexai/VertexAISnippets/Preview Content/Preview Assets.xcassets/Contents.json b/vertexai/VertexAISnippets/Preview Content/Preview Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/vertexai/VertexAISnippets/Preview Content/Preview Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/vertexai/VertexAISnippets/VertexAISnippets.entitlements b/vertexai/VertexAISnippets/VertexAISnippets.entitlements new file mode 100644 index 00000000..f2ef3ae0 --- /dev/null +++ b/vertexai/VertexAISnippets/VertexAISnippets.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.files.user-selected.read-only + + + diff --git a/vertexai/VertexAISnippets/VertexAISnippets.swift b/vertexai/VertexAISnippets/VertexAISnippets.swift new file mode 100644 index 00000000..ea18b7fb --- /dev/null +++ b/vertexai/VertexAISnippets/VertexAISnippets.swift @@ -0,0 +1,454 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#if canImport(UIKit) +import UIKit +#else +import AppKit +#endif + +// [START import_vertexai] +import FirebaseVertexAI +import FirebaseCore +// [END import_vertexai] + +class Snippets { + + var model: GenerativeModel! + + func initializeModel() { + // [START initialize_model] + // Initialize the Vertex AI service + let vertex = VertexAI.vertexAI() + + // Initialize the generative model with a model that supports your use case + // Gemini 1.5 models are versatile and can be used with all API capabilities + let model = vertex.generativeModel(modelName: "gemini-1.5-flash") + // [END initialize_model] + + self.model = model + } + + func configureModel() { + let vertex = VertexAI.vertexAI() + + // [START configure_model] + let config = GenerationConfig( + temperature: 0.9, + topP: 0.1, + topK: 16, + maxOutputTokens: 200, + stopSequences: ["red"] + ) + + let model = vertex.generativeModel( + modelName: "gemini-1.5-flash", + generationConfig: config + ) + // [END configure_model] + } + + func safetySettings() { + let vertex = VertexAI.vertexAI() + + // [START safety_settings] + let model = vertex.generativeModel( + modelName: "gemini-1.5-flash", + safetySettings: [ + SafetySetting(harmCategory: .harassment, threshold: .blockOnlyHigh) + ] + ) + // [END safety_settings] + } + + func multiSafetySettings() { + let vertex = VertexAI.vertexAI() + + // [START multi_safety_settings] + let harassmentSafety = SafetySetting(harmCategory: .harassment, threshold: .blockOnlyHigh) + let hateSpeechSafety = SafetySetting(harmCategory: .hateSpeech, threshold: .blockMediumAndAbove) + + let model = vertex.generativeModel( + modelName: "gemini-1.5-flash", + safetySettings: [harassmentSafety, hateSpeechSafety] + ) + // [END multi_safety_settings] + } + + func sendTextOnlyPromptStreaming() async throws { + // [START text_gen_text_only_prompt_streaming] + // Provide a prompt that contains text + let prompt = "Write a story about a magic backpack." + + // To stream generated text output, call generateContentStream with the text input + let contentStream = try model.generateContentStream(prompt) + for try await chunk in contentStream { + if let text = chunk.text { + print(text) + } + } + // [END text_gen_text_only_prompt_streaming] + } + + func sendTextOnlyPromt() async throws { + // [START text_gen_text_only_prompt] + // Provide a prompt that contains text + let prompt = "Write a story about a magic backpack." + + // To generate text output, call generateContent with the text input + let response = try await model.generateContent(prompt) + if let text = response.text { + print(text) + } + // [END text_gen_text_only_prompt] + } + + func sendMultimodalPromptStreaming() async throws { + // [START text_gen_multimodal_one_image_prompt_streaming] + #if canImport(UIKit) + guard let image = UIImage(named: "image") else { fatalError() } + #else + guard let image = NSImage(named: "image") else { fatalError() } + #endif + + // Provide a text prompt to include with the image + let prompt = "What's in this picture?" + + // To stream generated text output, call generateContentStream and pass in the prompt + let contentStream = try model.generateContentStream(image, prompt) + for try await chunk in contentStream { + if let text = chunk.text { + print(text) + } + } + // [END text_gen_multimodal_one_image_prompt_streaming] + } + + func sendMultimodalPrompt() async throws { + // [START text_gen_multimodal_one_image_prompt] + // Provide a text prompt to include with the image + #if canImport(UIKit) + guard let image = UIImage(named: "image") else { fatalError() } + #else + guard let image = NSImage(named: "image") else { fatalError() } + #endif + + let prompt = "What's in this picture?" + + // To generate text output, call generateContent and pass in the prompt + let response = try await model.generateContent(image, prompt) + if let text = response.text { + print(text) + } + // [END text_gen_multimodal_one_image_prompt] + } + + func multiImagePromptStreaming() async throws { + // [START text_gen_multimodal_multi_image_prompt_streaming] + #if canImport(UIKit) + guard let image1 = UIImage(named: "image1") else { fatalError() } + guard let image2 = UIImage(named: "image2") else { fatalError() } + #else + guard let image1 = NSImage(named: "image1") else { fatalError() } + guard let image2 = NSImage(named: "image2") else { fatalError() } + #endif + + // Provide a text prompt to include with the images + let prompt = "What's different between these pictures?" + + // To stream generated text output, call generateContentStream and pass in the prompt + let contentStream = try model.generateContentStream(image1, image2, prompt) + for try await chunk in contentStream { + if let text = chunk.text { + print(text) + } + } + // [END text_gen_multimodal_multi_image_prompt_streaming] + } + + func multiImagePrompt() async throws { + // [START text_gen_multimodal_multi_image_prompt] + #if canImport(UIKit) + guard let image1 = UIImage(named: "image1") else { fatalError() } + guard let image2 = UIImage(named: "image2") else { fatalError() } + #else + guard let image1 = NSImage(named: "image1") else { fatalError() } + guard let image2 = NSImage(named: "image2") else { fatalError() } + #endif + + // Provide a text prompt to include with the images + let prompt = "What's different between these pictures?" + + // To generate text output, call generateContent and pass in the prompt + let response = try await model.generateContent(image1, image2, prompt) + if let text = response.text { + print(text) + } + // [END text_gen_multimodal_multi_image_prompt] + } + + func textAndVideoPrompt() async throws { + // [START text_gen_multimodal_video_prompt] + guard let fileURL = Bundle.main.url(forResource: "sample", + withExtension: "mp4") else { fatalError() } + let video = try Data(contentsOf: fileURL) + let prompt = "What's in this video?" + let videoContent = InlineDataPart(data: video, mimeType: "video/mp4") + + // To generate text output, call generateContent and pass in the prompt + let response = try await model.generateContent(videoContent, prompt) + if let text = response.text { + print(text) + } + // [END text_gen_multimodal_video_prompt] + } + + func textAndVideoPromptStreaming() async throws { + // [START text_gen_multimodal_video_prompt_streaming] + guard let fileURL = Bundle.main.url(forResource: "sample", + withExtension: "mp4") else { fatalError() } + let video = try Data(contentsOf: fileURL) + let prompt = "What's in this video?" + let videoContent = InlineDataPart(data: video, mimeType: "video/mp4") + + // To stream generated text output, call generateContentStream and pass in the prompt + let contentStream = try model.generateContentStream(videoContent, prompt) + for try await chunk in contentStream { + if let text = chunk.text { + print(text) + } + } + // [END text_gen_multimodal_video_prompt_streaming] + } + + func chatStreaming() async throws { + // [START chat_streaming] + // Optionally specify existing chat history + let history = [ + ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."), + ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"), + ] + + // Initialize the chat with optional chat history + let chat = model.startChat(history: history) + + // To stream generated text output, call sendMessageStream and pass in the message + let contentStream = try chat.sendMessageStream("How many paws are in my house?") + for try await chunk in contentStream { + if let text = chunk.text { + print(text) + } + } + // [END chat_streaming] + } + + func chat() async throws { + // [START chat] + // Optionally specify existing chat history + let history = [ + ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."), + ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"), + ] + + // Initialize the chat with optional chat history + let chat = model.startChat(history: history) + + // To generate text output, call sendMessage and pass in the message + let response = try await chat.sendMessage("How many paws are in my house?") + if let text = response.text { + print(text) + } + // [END chat] + } + + func countTokensText() async throws { + // [START count_tokens_text] + let response = try await model.countTokens("Why is the sky blue?") + print("Total Tokens: \(response.totalTokens)") + print("Total Billable Characters: \(response.totalBillableCharacters ?? 0)") + // [END count_tokens_text] + } + + func countTokensTextAndImage() async throws { +#if canImport(UIKit) + guard let image = UIImage(named: "image") else { fatalError() } +#else + guard let image = NSImage(named: "image") else { fatalError() } +#endif + // [START count_tokens_text_image] + let response = try await model.countTokens(image, "What's in this picture?") + print("Total Tokens: \(response.totalTokens)") + print("Total Billable Characters: \(response.totalBillableCharacters ?? 0)") + // [END count_tokens_text_image] + } + + func countTokensMultiImage() async throws { +#if canImport(UIKit) + guard let image1 = UIImage(named: "image1") else { fatalError() } + guard let image2 = UIImage(named: "image2") else { fatalError() } +#else + guard let image1 = NSImage(named: "image1") else { fatalError() } + guard let image2 = NSImage(named: "image2") else { fatalError() } +#endif + // [START count_tokens_multi_image] + let response = try await model.countTokens(image1, image2, "What's in this picture?") + print("Total Tokens: \(response.totalTokens)") + print("Total Billable Characters: \(response.totalBillableCharacters ?? 0)") + // [END count_tokens_multi_image] + } + + func countTokensChat() async throws { + // [START count_tokens_chat] + let chat = model.startChat() + let history = chat.history + let message = ModelContent(role: "user", parts: "Why is the sky blue?") + let contents = history + [message] + let response = try await model.countTokens(contents) + print("Total Tokens: \(response.totalTokens)") + print("Total Billable Characters: \(response.totalBillableCharacters ?? 0)") + // [END count_tokens_chat] + } + + func setSafetySetting() { + // [START set_one_safety_setting] + let model = VertexAI.vertexAI().generativeModel( + modelName: "gemini-1.5-flash", + safetySettings: [ + SafetySetting(harmCategory: .harassment, threshold: .blockOnlyHigh) + ] + ) + // [END set_one_safety_setting] + } + + func setMultipleSafetySettings() { + // [START set_multi_safety_settings] + let harassmentSafety = SafetySetting(harmCategory: .harassment, threshold: .blockOnlyHigh) + let hateSpeechSafety = SafetySetting(harmCategory: .hateSpeech, threshold: .blockMediumAndAbove) + + let model = VertexAI.vertexAI().generativeModel( + modelName: "gemini-1.5-flash", + safetySettings: [harassmentSafety, hateSpeechSafety] + ) + // [END set_multi_safety_settings] + } + + // MARK: - Function Calling + + func functionCalling() async throws { + // [START create_function] + func makeAPIRequest(currencyFrom: String, currencyTo: String) -> JSONObject { + // This hypothetical API returns a JSON such as: + // {"base":"USD","rates":{"SEK": 10.99}} + return [ + "base": .string(currencyFrom), + "rates": .object([currencyTo: .number(10.99)]), + ] + } + // [END create_function] + + // [START create_function_metadata] + let getExchangeRate = FunctionDeclaration( + name: "getExchangeRate", + description: "Get the exchange rate for currencies between countries", + parameters: [ + "currencyFrom": Schema.string( + description: "The currency to convert from." + ), + "currencyTo": Schema.string( + description: "The currency to convert to." + ), + ] + ) + // [END create_function_metadata] + + // [START initialize_model_function] + // Initialize the Vertex AI service + let vertex = VertexAI.vertexAI() + + // Initialize the generative model + // Use a model that supports function calling, like a Gemini 1.5 model. + let model = vertex.generativeModel( + modelName: "gemini-1.5-flash", + // Specify the function declaration. + tools: [Tool.functionDeclarations([getExchangeRate])] + ) + // [END initialize_model_function] + + // [START generate_function_call] + let chat = model.startChat() + + let prompt = "How much is 50 US dollars worth in Swedish krona?" + + // Send the message to the generative model + let response1 = try await chat.sendMessage(prompt) + + // Check if the model responded with a function call + guard let functionCall = response1.functionCalls.first else { + fatalError("Model did not respond with a function call.") + } + // Print an error if the returned function was not declared + guard functionCall.name == "getExchangeRate" else { + fatalError("Unexpected function called: \(functionCall.name)") + } + // Verify that the names and types of the parameters match the declaration + guard case let .string(currencyFrom) = functionCall.args["currencyFrom"] else { + fatalError("Missing argument: currencyFrom") + } + guard case let .string(currencyTo) = functionCall.args["currencyTo"] else { + fatalError("Missing argument: currencyTo") + } + + // Call the hypothetical API + let apiResponse = makeAPIRequest(currencyFrom: currencyFrom, currencyTo: currencyTo) + + // Send the API response back to the model so it can generate a text response that can be + // displayed to the user. + let response = try await chat.sendMessage([ModelContent( + role: "function", + parts: [FunctionResponsePart(name: functionCall.name, response: apiResponse)] + )]) + + // Log the text response. + guard let modelResponse = response.text else { + fatalError("Model did not respond with text.") + } + print(modelResponse) + // [END generate_function_call] + } + + func functionCallingModes() { + let getExchangeRate = FunctionDeclaration( + name: "getExchangeRate", + description: "Get the exchange rate for currencies between countries", + parameters: [:] + ) + + // [START function_modes] + let model = VertexAI.vertexAI().generativeModel( + // Setting a function calling mode is only available in Gemini 1.5 Pro + modelName: "gemini-1.5-pro", + // Pass the function declaration + tools: [Tool.functionDeclarations([getExchangeRate])], + toolConfig: ToolConfig( + // Only call functions (model won't generate text) + functionCallingConfig: FunctionCallingConfig.any( + // This should only be set when the Mode is .any. + allowedFunctionNames: ["getExchangeRate"] + ) + ) + ) + // [END function_modes] + } + +} diff --git a/vertexai/VertexAISnippets/VertexAISnippetsApp.swift b/vertexai/VertexAISnippets/VertexAISnippetsApp.swift new file mode 100644 index 00000000..cc626444 --- /dev/null +++ b/vertexai/VertexAISnippets/VertexAISnippetsApp.swift @@ -0,0 +1,24 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SwiftUI + +@main +struct VertexAISnippetsApp: App { + var body: some Scene { + WindowGroup { + ContentView() + } + } +}