How to sign in with apple for web with firebase

Issue #668

Authenticate Using Apple with JavaScript

Use Firebase JS SDK

Configure Sign in with Apple for the web

Go to Certificates, Identifiers & Profiles -> Identifier create 2 ids: App ID and Service ID

For example: I have App ID com.onmyway133.myapp and Service ID com.onmyway133.myweb

Screenshot 2020-06-16 at 09 20 34

Remember that to view App ID or Service ID, there’s dropdown menu on the right

Screenshot 2020-06-16 at 09 21 20

For App ID, enable

  • Associated Domains
  • Sign In with Apple: Enable it as Primary App ID

For Service ID, use firebase callback url

Associate domain

Add apple-app-site-association in public folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"applinks": {
"details": [
{
"appIDs": ["T78DK947F2.com.onmyway133.myapp"],
"components": [
{
"#": "no_universal_links",
"exclude": true,
"comment": "Matches any URL whose fragment equals no_universal_links and instructs the system not to open it as a universal link"
}
]
}
]
},
"webcredentials": {
"apps": [ "T78DK947F2.com.onmyway133.myweb" ]
}
}

Private key

Go to Keys and create new auth key. Configure that key with the primary App ID above

Screenshot 2020-06-16 at 09 24 05

Configure in Firebase

Go to Sign in providers and enable Apple sign in.

Fill in

  • Service ID identifier (com.onmyway133.myweb)
  • OAuth code flow configuration: fill in your team id, key id and key secret content.
Screenshot 2020-06-16 at 09 25 23

How to use firebase cloud functions

Issue #667

Use node 10

Edit package.json

1
2
3
"engines": {
"node": "10"
},

Secret key

Go to settings/serviceaccounts/adminsdk, download secret key in form of json and place it in lib/config.json

1
2
3
4
5
6
const serviceAccount = require('./config.json')

admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://my-app-4b968.firebaseio.com"
})

Local serve

This builds and spins up emulator to test

1
npm run serve

CORS

1
response.set('Access-Control-Allow-Origin', '*');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var cors = require('cors');

// my function
var helloFn = function helloFn(req, res) {
res.status(200)
.send('Hello, Functions\n');
};

// CORS and Cloud Functions export logic
exports.hello = function hello(req, res) {
var corsFn = cors();
corsFn(req, res, function() {
helloFn(req, res);
});
}

How to use Firebase Crashlytics in macOS app

Issue #585

New Firebase Crashlytics

Follow the new Firebase Crashlytics guide Get started with Firebase Crashlytics using the Firebase Crashlytics SDK

CocoaPods

Specify FirebaseCore for community managed macOS version of Firebase

1
2
3
4
5
6
7
8
9
10
platform :osx, '10.13'

target 'MyMacApp' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!

pod 'FirebaseCore'
pod 'Firebase/Crashlytics'

end

Signing and capabilities

Under Hardware runtime, check Disable library validation
Under App sandbox, enable Outgoing connections (Client)

Run script

Add a new run script build phrase to the last

1
"${PODS_ROOT}/FirebaseCrashlytics/run"

In that build phase, under Input Files, specify dsym and info plist file for dsym to be recognized

1
2
$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)
${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}

AppDelegate

1
2
3
4
import FirebaseCore
import FirebaseCrashlytics

FirebaseApp.configure()

How to use Firebase in macOS

Issue #501

  • Use Catalyst
  • Add to CocoaPods
1
2
3
4
5
6
7
8
9
platform :ios, '13.0'

target 'MyApp' do
use_frameworks!

pod 'FirebaseCore'
pod 'Firebase/Firestore'

end

Troubleshooting

Select a team for gRPC-C++-gRPCCertificates-Cpp

Screenshot 2019-11-12 at 14 53 03

FIRAnalyticsConnector: building for Mac Catalyst, but linking in object file built for iOS Simulator

https://stackoverflow.com/questions/57666155/firanalyticsconnector-building-for-mac-catalyst-but-linking-in-object-file-bui

The problem was related to the difference between Firebase/Core and FirebaseCore. The first is a subspec of the Firebase pod that depends on FirebaseAnalytics. The second is only the FirebaseCore pod. Only the latter should be used for macOS.

How to use Firebase RemoteConfig

Issue #493

Declare in Podfile

1
2
pod 'Firebase/Core'
pod 'Firebase/RemoteConfig'

Use RemoteConfigHandler to encapsulate logic. We introduce Key with CaseIterable and defaultValue of type NSNumber to manage default values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import Firebase
import FirebaseRemoteConfig

final class RemoteConfigHandler {
let remoteConfig: RemoteConfig

enum Key: String, CaseIterable {
case interval = "fetch_interval"

var defaultValue: NSNumber {
switch self {
case .periodicGetSalons: return NSNumber(value: 300)
}
}
}

init() {
self.remoteConfig = RemoteConfig.remoteConfig()

let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 0
self.remoteConfig.configSettings = settings

let map = Key.allCases.reduce([String: NSObject](), { map, key in
var map = map
map[key.rawValue] = key.defaultValue
return map
})

self.remoteConfig.setDefaults(map)
}

func update() {
self.remoteConfig.fetchAndActivate(completionHandler: { status, error in
print(status, error as Any)
})
}

var fetchInterval: TimeInterval {
return getValue(key: .interval, transform: { $0.doubleValue })
}

private func getValue<T>(key: Key, transform: (NSNumber) -> T) -> T {
let number = remoteConfig.configValue(forKey: key.rawValue).numberValue ?? key.defaultValue
return transform(number)
}
}

How to use Firebase SDK with Firestore for React Native

Issue #260

Original post https://medium.com/react-native-training/firebase-sdk-with-firestore-for-react-native-apps-in-2018-aa89a67d6934


At Firebase Dev Summit 2017, Google introduced Firestore as fully-managed NoSQL document database for mobile and web app development. Compared to Firebase Realtime Database, it has better querying and more structured data, together with ease manual fetching of data.

The new structure of collection and document is probably the eye catching, this makes data more intuitive to users and query a breeze.

From [https://firebase.googleblog.com/2017/10/cloud-firestore-for-rtdb-developers.html](https://firebase.googleblog.com/2017/10/cloud-firestore-for-rtdb-developers.html)From https://firebase.googleblog.com/2017/10/cloud-firestore-for-rtdb-developers.html

In this post, I will show how to setup Firebase Cloud Firestore in React Native apps for both iOS and Android through, of course, some pain points. Then we create and fetch document in Firestore database.

Firebase Javascript SDK

My first option is to go with Firebase Javascript SDK, as it worked well for me with Firebase Realtime Database. My use case is to just fetch and update Firestore collections, I think it does not involve much of native features. Furthermore, when possible I try to avoid native code as much as possible when dealing with React Native.

So let’s try Get started with Cloud Firestore

npm install firebase

The version I install is 5.4.0. Next, import firebase and note that we need to import firestore as well

const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");

document is not defined

This issue made me bang against my desk for a while. As people have pointed out, it is because of document being accessed.

var BrowserPlatform = /** @class */ (function () {
    function BrowserPlatform() {
        this.emptyByteString = '';
        this.document = document; // delete this line
        this.window = window; // delete this line
        this.base64Available = typeof atob !== 'undefined';
    }

The firestore component in the current Firebase Javascript SDK does not fully support React Native, so we need to work around or use beta version with npm install firebase@next . In the mean time, let’s try React Native Firebase.

React Native Firebase

Reading over at Cloud Firestore Library and framework integrations, React Native Firebase is recommended. Although some features from the Firebase Web SDK will generally work with React Native, it is mainly built for the web and as such has a limited compatible feature set.

Source: [https://rnfirebase.io/docs/v4.3.x/getting-started](https://rnfirebase.io/docs/v4.3.x/getting-started)Source: https://rnfirebase.io/docs/v4.3.x/getting-started

The below article and their starter app is the guiding star. The integration with native code in iOS and Android can be painful, but I React Native Firebase is very powerful as it has up-to-date wrappers around native Firebase SDK.

Let ‘s npm install react-native-firebase , the current version is 4.3.8 , and follow manual setup guide for existing project, this helps you learn more about the process and the bootstrap script.

A quick look

First you need to Firebase console and add a project. A project allows many apps to stay, for example I have 4 apps (2 iOS, 2 Android) that have access to Firestore database.

Head over to Database in the left menu, we can see a quick look into Firestore and its collection/document structure

Setup for iOS

Follow iOS Installation Guide

Firstly, download GoogleService-Info.plist and place it in the correct folder, make sure it has been added to project via Xcode. Otherwise Firebase SDK causes app to crash right after start.

Then add #import <Firebase.h> to AppDelegate.m and [FIRApp configure]; to function didFinishLaunchingWithOptions . Next create Podfile with pod init inside ios folder. For Firestore, you need Firebase/Firestore to prevent the error below

You attempted to use a firebase module that’s not installed natively on your iOS project by calling firebase.firestore()

And you shouldn’t use use_frameworks! as it gives error ‘FirebaseCore/FIRAnalyticsConfiguration.h’ file not found

platform :ios, '9.0'

target 'FoodshopGuest' do
  pod 'Firebase/Core', '~> 5.3.0'
  pod 'Firebase/Firestore', '~> 5.3.0'
end

If you get framework not found FirebaseAnalytics , then make sure each target has $(inherited) at the top for Framework Search Paths

Then run react-native link react-native-firebase and you should be good for iOS.

Setup for Android

Android is a bit less straightforward to setup than iOS. But it’s not impossible. Let’s follow Android Installation guide.

Firstly, place google-services.json in android/app/google-services.json . Let’s also use Gradle 4.4 and Google Play Services 15.0.1 . Change gradle/gradle-wrapper.properties to use

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Below is my project build.gradle with compileSdkVersion 27 and buildToolsVersion 27.0.3 . Make sure google() stays above jcenter()

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            url '[https://maven.google.com/'](https://maven.google.com/')
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath 'com.google.gms:google-services:4.0.1'

// NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

ext {
    buildToolsVersion = "27.0.3"
    minSdkVersion = 16
    compileSdkVersion = 27
    targetSdkVersion = 26
    supportLibVersion = "26.1.0"
}

For my app module build.gradle , let’s have apply plugin: ‘com.google.gms.google-services’ at the very bottom of the file, this is important. In dependencies section, you must have com.google.firebase:firebase-firestore to include Firestore component.

dependencies {
    implementation project(':react-native-firebase')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"

// Firebase dependencies
    implementation "com.google.android.gms:play-services-base:15.0.1"
    implementation "com.google.firebase:firebase-core:16.0.1"
    implementation "com.google.firebase:firebase-firestore:17.0.2"

}

Make sure there is no duplication of project(‘:react-native-firebase’) . And since we are using Gradle 4, let’s use implementation instead of compile
What’s the difference between implementation and compile in Gradle?
This site uses cookies to deliver our services and to show you relevant ads and job listings. By using our site, you…stackoverflow.com

Because of Firestore, let’s follow react-native-firebase-starter to fix heap problem

dexOptions {
    javaMaxHeapSize "4g"
}

multiDexEnabled true

If you get Native module RNFirebaseModule tried to override FNFirebaseModule

Native module RNFirebaseModule tried to override FNFirebaseModule for module name Firebase. If this was your intention, set `canOverrideExistingModule=true

Then make sure your MainApplication.java has no duplication for new RNFirebasePackage() . Here is my MainApplication.java , note that you need import io.invertase.firebase.firestore.RNFirebaseFirestorePackage; in order to use RNFirebaseFirestorePackage

package com.fantageek.foodshophost;

import android.app.Application;

import com.facebook.react.ReactApplication;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    [@Override](http://twitter.com/Override)
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

[@Override](http://twitter.com/Override)
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new RNFirebasePackage(),
          new RNFirebaseFirestorePackage()
      );
    }

[@Override](http://twitter.com/Override)
    protected String getJSMainModuleName() {
      return "index";
    }
  };

[@Override](http://twitter.com/Override)
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

[@Override](http://twitter.com/Override)
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

My rule of thumb is that you should always use Android Studio to perform Gradle sync or Build projectThere you should be able to see compile issues much easier. With all the steps above, compilation should succeed.

One problem with running React Native on Android, if after react-native run-android and Metro keeps showing Loading dependency graph, done , then you should start emulator via Android Studio -> AVD Manager or adb , the app should be already installed in the emulator, open the app and Metro will start loading again.

Trying Firestore

React Native Firebase should give you similar APIs to those in the web, so learn from Get data with Cloud Firestore for how to get or set documents.

I like to organise services in separate files, here is how to reference firestore and load document.

import firebase from 'react-native-firebase'

class FirebaseService {
  constructor() {
    this.ref = firebase.firestore().collection('people')
  }

async load(id) {
    const doc = await this.ref.doc(id).get()
    if (doc.exists) {
      return doc.data()
    } else {
      const defaultDoc = {
        name: "ABC",
        age: 2
      }

await this.ref.doc(id).set(defaultDoc)
      return doc
    }
  }
}

export const firebaseService = new FirebaseService()

Where to go from here

I hope this article helps in setting up Firebase SDK in React Native apps. Below are some resources that helps you explore further. The react-native-firebase-starter contains awesome reference code if you get into any troubles with react-native-firebase.
Getting started with Cloud Firestore on React Native
A week ago, Firebase announced Cloud Firestore, an awesome NoSQL document database that complements the existing…blog.invertase.io

invertase/react-native-firebase-starter
react-native-firebase-starter - 🎁 A bare-bones react native app with react-native-firebase pre-integrated so you can…github.com