Merge commit 'a129994' into omer_links

This commit is contained in:
Omer Levy 2017-08-31 19:19:25 +03:00
commit 79090f59a6
119 changed files with 4898 additions and 908 deletions

10
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,10 @@
(Please write your issue here along with the environment details below. Include any key files which will help us to debug, such as your `Podfile` and/or `app/build.gradle` file).
### Environment
1. Target Platform (e.g. iOS, Android):
2. Development Operating System (e.g. macOS Sierra, Windows 10):
3. Build tools (Xcode or Android Studio version, iOS or Android SDK version, if relevant):
4. React Native version (e.g. 0.45.1):
5. RNFirebase Version (e.g. 2.0.2):

3
.gitignore vendored
View File

@ -11,7 +11,8 @@ npm-debug.log
project.xcworkspace/
xcuserdata/
# Android
# Example
example/demo/ios/demo.xcworkspace/
# Built application files
**/android/**/build/

View File

@ -1,7 +1,7 @@
node_modules
npm-debug.log
*.DS_Store
.github
# Xcode
*.pbxuser
*.mode1v3
@ -11,7 +11,8 @@ npm-debug.log
project.xcworkspace/
xcuserdata/
# Android
# Example
example/
# Built application files
android/*/build/
@ -63,4 +64,3 @@ yarn.lock
tests
lib/.watchmanconfig
buddybuild_postclone.sh

View File

@ -30,9 +30,9 @@ RNFirebase is a _light-weight_ layer sitting on-top of the native Firebase libra
Although the [Firebase Web SDK](https://www.npmjs.com/package/firebase) library will work with React Native, it is mainly built for the web.
RNFirebase provides a JavaScript bridge to the native Firebase SDKs for both iOS and Android therefore Firebase will run on the native thread, allowing the rest of your app to run on the [JS thread](https://facebook.github.io/react-native/docs/performance.html#javascript-frame-rate). The Firebase Web SDK also runs on the JS thread, therefore potentially affecting the frame rate causing jank with animations, touch events etc.
RNFirebase provides a JavaScript bridge to the native Firebase SDKs for both iOS and Android therefore Firebase will run on the native thread, allowing the rest of your app to run on the [JS thread](https://facebook.github.io/react-native/docs/performance.html#javascript-frame-rate). The Firebase Web SDK also runs on the JS thread, therefore potentially affecting the frame rate causing jank with animations, touch events etc.
The native SDKs also allow us to hook into device sdk's which are not possible with the web SDK, for example crash reporting, offline realtime database support, analyics and more!
The native SDKs also allow us to hook into device sdk's which are not possible with the web SDK, for example crash reporting, offline realtime database support, analytics and more!
All in all, RNFirebase provides much faster performance (~2x) over the web SDK and provides device sdk's not found in the web sdk (see the feature table below).
@ -41,7 +41,7 @@ All in all, RNFirebase provides much faster performance (~2x) over the web SDK a
> The Web SDK column indicates what modules from the Firebase Web SDK are usable with React Native.
| Firebase Features | v1 | [v2](https://github.com/invertase/react-native-firebase/pull/130) | Web SDK |
| Firebase Features | v1 | v2 | Web SDK |
| ---------------------- | :---: | :---: | :---: |
| AdMob | ❌ | ✅ | ❌ |
| Analytics             | ✅ | ✅ | ❌ |
@ -54,17 +54,23 @@ All in all, RNFirebase provides much faster performance (~2x) over the web SDK a
| Performance Monitoring | ✅ | ✅ | ❌ |
| Realtime Database | ✅ | ✅ | ✅ |
| - Offline Persistance | ✅ | ✅ | ❌ |
| - Transactions | ✅ | ✅ | ✅ |
| Remote Config | ✅ | ✅ | ❌ |
| Storage | ✅ | ✅ | ❌ |
---
### Supported versions - Firebase / React Native
### Supported versions - React Native / Firebase
> The table below shows the minimum supported versions of the Firebase SDKs and React Native
> The table below shows the supported version of `react-native-firebase` for different React Native versions
| | v1 | [v2](https://github.com/invertase/react-native-firebase/pull/130)
| | v0.36 - v0.39 | v0.40 - v0.46 | v0.47 +
| ------------------------------- | :---: | :---: | :---: |
| react-native-firebase | 1.X.X | 2.X.X | 2.1.X |
> The table below shows the minimum supported versions of the Firebase SDKs for each version of `react-native-firebase`
| | v1 | v2 |
| ---------------------- | :---: | :---: |
| React Native | 0.36.0+ | 0.40.0 + |
| Firebase Android SDK | 10.2.0+ | 11.0.0 + |
| Firebase iOS SDK | 3.15.0+ | 4.0.0 + |

View File

@ -16,4 +16,5 @@ Pod::Spec.new do |s|
s.platform = :ios, "8.0"
s.preserve_paths = 'README.md', 'package.json', '*.js'
s.source_files = 'ios/RNFirebase/**/*.{h,m}'
s.dependency 'React'
end

View File

@ -38,7 +38,7 @@ public class RNFirebasePackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -36,7 +36,7 @@ public class RNFirebaseAdMobPackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -35,7 +35,7 @@ public class RNFirebaseAnalyticsPackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -23,6 +23,7 @@ import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.ActionCodeResult;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
@ -502,6 +503,107 @@ public class RNFirebaseAuth extends ReactContextBaseJavaModule {
}
}
/**
* confirmPasswordReset
*
* @param code
* @param newPassword
* @param promise
*/
@ReactMethod
public void confirmPasswordReset(String code, String newPassword, final Promise promise) {
Log.d(TAG, "confirmPasswordReset");
mAuth.confirmPasswordReset(code, newPassword)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "confirmPasswordReset:onComplete:success");
promiseNoUser(promise, false);
} else {
Exception exception = task.getException();
Log.e(TAG, "confirmPasswordReset:onComplete:failure", exception);
promiseRejectAuthException(promise, exception);
}
}
});
}
/**
* applyActionCode
*
* @param code
* @param promise
*/
@ReactMethod
public void applyActionCode(String code, final Promise promise) {
Log.d(TAG, "applyActionCode");
mAuth.applyActionCode(code).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "applyActionCode:onComplete:success");
promiseNoUser(promise, false);
} else {
Exception exception = task.getException();
Log.e(TAG, "applyActionCode:onComplete:failure", exception);
promiseRejectAuthException(promise, exception);
}
}
});
}
/**
* @param code
* @param promise
*/
@ReactMethod
public void checkActionCode(String code, final Promise promise) {
Log.d(TAG, "checkActionCode");
mAuth.checkActionCode(code).addOnCompleteListener(new OnCompleteListener<ActionCodeResult>() {
@Override
public void onComplete(@NonNull Task<ActionCodeResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "checkActionCode:onComplete:success");
ActionCodeResult result = task.getResult();
WritableMap writableMap = Arguments.createMap();
WritableMap dataMap = Arguments.createMap();
dataMap.putString("email", result.getData(ActionCodeResult.EMAIL));
dataMap.putString("fromEmail", result.getData(ActionCodeResult.FROM_EMAIL));
writableMap.putMap("data", dataMap);
String actionType = "UNKNOWN";
switch (result.getOperation()) {
case ActionCodeResult.ERROR:
actionType = "ERROR";
break;
case ActionCodeResult.VERIFY_EMAIL:
actionType = "VERIFY_EMAIL";
break;
case ActionCodeResult.RECOVER_EMAIL:
actionType = "RECOVER_EMAIL";
break;
case ActionCodeResult.PASSWORD_RESET:
actionType = "PASSWORD_RESET";
break;
}
writableMap.putString("actionType", actionType);
promise.resolve(writableMap);
} else {
Exception exception = task.getException();
Log.e(TAG, "checkActionCode:onComplete:failure", exception);
promiseRejectAuthException(promise, exception);
}
}
});
}
/**
* link
*
@ -541,6 +643,38 @@ public class RNFirebaseAuth extends ReactContextBaseJavaModule {
}
}
/**
* unlink
*
* @url https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseUser.html#unlink(java.lang.String)
* @param providerId
* @param promise
*/
@ReactMethod
public void unlink(final String providerId, final Promise promise) {
FirebaseUser user = mAuth.getCurrentUser();
Log.d(TAG, "unlink");
if (user != null) {
user.unlink(providerId)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "unlink:onComplete:success");
promiseWithUser(task.getResult().getUser(), promise);
} else {
Exception exception = task.getException();
Log.e(TAG, "unlink:onComplete:failure", exception);
promiseRejectAuthException(promise, exception);
}
}
});
} else {
promiseNoUser(promise, true);
}
}
/**
* reauthenticate
*
@ -645,28 +779,28 @@ public class RNFirebaseAuth extends ReactContextBaseJavaModule {
Log.d(TAG, "fetchProvidersForEmail");
mAuth.fetchProvidersForEmail(email)
.addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
@Override
public void onComplete(@NonNull Task<ProviderQueryResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "fetchProvidersForEmail:onComplete:success");
List<String> providers = task.getResult().getProviders();
WritableArray array = Arguments.createArray();
.addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
@Override
public void onComplete(@NonNull Task<ProviderQueryResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "fetchProvidersForEmail:onComplete:success");
List<String> providers = task.getResult().getProviders();
WritableArray array = Arguments.createArray();
if (providers != null) {
for(String provider : providers) {
array.pushString(provider);
}
if (providers != null) {
for (String provider : providers) {
array.pushString(provider);
}
promise.resolve(array);
} else {
Exception exception = task.getException();
Log.d(TAG, "fetchProvidersForEmail:onComplete:failure", exception);
promiseRejectAuthException(promise, exception);
}
promise.resolve(array);
} else {
Exception exception = task.getException();
Log.d(TAG, "fetchProvidersForEmail:onComplete:failure", exception);
promiseRejectAuthException(promise, exception);
}
});
}
});
}
/* ------------------
@ -786,6 +920,7 @@ public class RNFirebaseAuth extends ReactContextBaseJavaModule {
/**
* Converts a List of UserInfo instances into the correct format to match the web sdk
*
* @param providerData List<UserInfo> user.getProviderData()
* @return WritableArray array
*/

View File

@ -35,7 +35,7 @@ public class RNFirebaseAuthPackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -35,7 +35,7 @@ public class RNFirebaseRemoteConfigPackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -35,7 +35,7 @@ public class RNFirebaseCrashPackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -88,7 +88,6 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
DatabaseReference ref = mFirebaseDatabase.getReference(path);
Map<String, Object> m = Utils.recursivelyDeconstructReadableMap(props);
DatabaseReference.CompletionListener listener = new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
@ -99,6 +98,44 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
ref.setValue(m.get("value"), listener);
}
@ReactMethod
public void priority(
final String path,
final ReadableMap priority,
final Callback callback) {
DatabaseReference ref = mFirebaseDatabase.getReference(path);
Map<String, Object> priorityMap = Utils.recursivelyDeconstructReadableMap(priority);
DatabaseReference.CompletionListener listener = new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
handleCallback("priority", callback, error);
}
};
ref.setPriority(priorityMap.get("value"), listener);
}
@ReactMethod
public void withPriority(
final String path,
final ReadableMap data,
final ReadableMap priority,
final Callback callback) {
DatabaseReference ref = mFirebaseDatabase.getReference(path);
Map<String, Object> dataMap = Utils.recursivelyDeconstructReadableMap(data);
Map<String, Object> priorityMap = Utils.recursivelyDeconstructReadableMap(priority);
DatabaseReference.CompletionListener listener = new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
handleCallback("withPriority", callback, error);
}
};
ref.setValue(dataMap.get("value"), priorityMap.get("value"), listener);
}
@ReactMethod
public void update(final String path,
final ReadableMap props,
@ -299,7 +336,12 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
@ReactMethod
public void once(final int refId, final String path, final ReadableArray modifiers, final String eventName, final Callback callback) {
RNFirebaseDatabaseReference ref = this.getDBHandle(refId, path, modifiers);
ref.addOnceValueEventListener(callback);
if (eventName.equals("value")) {
ref.addOnceValueEventListener(callback);
} else {
ref.addChildOnceEventListener(eventName, callback);
}
}
/**

View File

@ -35,7 +35,7 @@ public class RNFirebaseDatabasePackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -5,6 +5,7 @@ import java.util.HashSet;
import java.util.List;
import android.support.annotation.Nullable;
import android.telecom.Call;
import android.util.Log;
import java.util.Map;
@ -113,7 +114,7 @@ public class RNFirebaseDatabaseReference {
}
}
public void addOnceValueEventListener(final Callback callback) {
void addOnceValueEventListener(final Callback callback) {
final ValueEventListener onceValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
@ -132,11 +133,66 @@ public class RNFirebaseDatabaseReference {
callback.invoke(err);
}
};
mQuery.addListenerForSingleValueEvent(onceValueEventListener);
Log.d(TAG, "Added OnceValueEventListener for refId: " + mRefId);
}
public void removeEventListener(int listenerId, String eventName) {
void addChildOnceEventListener(final String eventName, final Callback callback) {
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
if ("child_added".equals(eventName)) {
mQuery.removeEventListener(this);
WritableMap data = Utils.snapshotToMap("child_added", mRefId, null, mPath, dataSnapshot, previousChildName);
callback.invoke(null, data);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
if ("child_changed".equals(eventName)) {
mQuery.removeEventListener(this);
WritableMap data = Utils.snapshotToMap("child_changed", mRefId, null, mPath, dataSnapshot, previousChildName);
callback.invoke(null, data);
}
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
if ("child_removed".equals(eventName)) {
mQuery.removeEventListener(this);
WritableMap data = Utils.snapshotToMap("child_removed", mRefId, null, mPath, dataSnapshot, null);
callback.invoke(null, data);
}
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
if ("child_moved".equals(eventName)) {
mQuery.removeEventListener(this);
WritableMap data = Utils.snapshotToMap("child_moved", mRefId, null, mPath, dataSnapshot, previousChildName);
callback.invoke(null, data);
}
}
@Override
public void onCancelled(DatabaseError error) {
mQuery.removeEventListener(this);
WritableMap err = Arguments.createMap();
err.putInt("refId", mRefId);
err.putString("path", mPath);
err.putInt("code", error.getCode());
err.putString("details", error.getDetails());
err.putString("message", error.getMessage());
callback.invoke(err);
}
};
mQuery.addChildEventListener(childEventListener);
}
void removeEventListener(int listenerId, String eventName) {
if ("value".equals(eventName)) {
this.removeValueEventListener(listenerId);
} else {
@ -144,7 +200,7 @@ public class RNFirebaseDatabaseReference {
}
}
public boolean hasListeners() {
boolean hasListeners() {
return !mChildEventListeners.isEmpty() || !mValueEventListeners.isEmpty();
}

View File

@ -35,7 +35,7 @@ public class RNFirebaseMessagingPackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -35,7 +35,7 @@ public class RNFirebasePerformancePackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -35,7 +35,7 @@ public class RNFirebaseStoragePackage implements ReactPackage {
* listed here. Also listing a native module here doesn't imply that the JS implementation of it
* will be automatically included in the JS bundle.
*/
@Override
// TODO: Removed in 0.47.0. Here for backwards compatability
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

View File

@ -8,7 +8,7 @@
<div style="text-align: center;">
[![npm version](https://img.shields.io/npm/v/react-native-firebase.svg?style=flat-square)](https://www.npmjs.com/package/react-native-firebase)
[![NPM downloads](https://img.shields.io/npm/dm/react-native-firebase.svg?style=flat-square)](https://www.npmjs.com/package/react-native-firebase)
[![Package Quality](http://npm.packagequality.com/shield/react-native-firebase.svg?style=flat-square)](http://packagequality.com/#?package=react-native-firebase)
[![Package Quality](https://npm.packagequality.com/shield/react-native-firebase.svg?style=flat-square)](http://packagequality.com/#?package=react-native-firebase)
[![License](https://img.shields.io/npm/l/react-native-firebase.svg?style=flat-square)](/LICENSE)
[![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg?style=flat-square)](https://discord.gg/t6bdqMs)
[![Chat](https://img.shields.io/badge/chat-on%20gitter-a0e7a0.svg?style=flat-square)](https://gitter.im/invertase/react-native-firebase)
@ -21,7 +21,7 @@ RNFirebase is a _light-weight_ layer sitting on-top of the native Firebase libra
Although the [Firebase Web SDK](https://www.npmjs.com/package/firebase) library will work with React Native, it is mainly built for the web.
RNFirebase provides a JavaScript bridge to the native Firebase SDKs for both iOS and Android therefore Firebase will run on the native thread, allowing the rest of your app to run on the [JS thread](https://facebook.github.io/react-native/docs/performance.html#javascript-frame-rate). The Firebase Web SDK also runs on the JS thread, therefore potentially affecting the frame rate causing jank with animations, touch events etc.
RNFirebase provides a JavaScript bridge to the native Firebase SDKs for both iOS and Android therefore Firebase will run on the native thread, allowing the rest of your app to run on the [JS thread](https://facebook.github.io/react-native/docs/performance.html#javascript-frame-rate). The Firebase Web SDK also runs on the JS thread, therefore potentially affecting the frame rate causing jank with animations, touch events etc.
The native SDKs also allow us to hook into device sdk's which are not possible with the web SDK, for example crash reporting, offline realtime database support, analyics and more!
@ -32,29 +32,35 @@ All in all, RNFirebase provides much faster performance (~2x) over the web SDK a
## Supported Firebase Features
> The Web SDK column indicates what modules from the Firebase Web SDK are usable within React Native.
| Firebase Features | v1 | [v2](https://github.com/invertase/react-native-firebase/pull/130) | Web SDK |
| Firebase Features | v1 | v2 | Web SDK |
| ---------------------- | :---: | :---: | :---: |
| AdMob | ❌ | ✅ | ❌ |
| Analytics             | ✅ | ✅ | ❌ |
| App Indexing           | ❌ | ❌ | ❌ |
| Authentication | ✅ | ✅ | ✅ |
| Cloud Messaging | ✅ | ✅ | ❌ |
| Cloud Messaging (FCM) | ✅ | ✅ | ❌ |
| Crash Reporting | ✅ | ✅ | ❌ |
| Dynamic Links | ❌ | ❌ | ❌ |
| Invites | ❌ | ❌ | ❌ |
| Performance Monitoring | ✅ | ✅ | ❌ |
| Realtime Database | ✅ | ✅ | ✅ |
| - Offline Persistance | ✅ | ✅ | ❌ |
| - Offline Persistence | ✅ | ✅ | ❌ |
| - Transactions | ✅ | ✅ | ✅ |
| Remote Config | ✅ | ✅ | ❌ |
| Storage | ✅ | ✅ | ❌ |
---
### Supported versions - Firebase / React Native
### Supported versions - React Native / Firebase
> The table below shows the minimum supported versions of the Firebase SDKs and React Native
> The table below shows the supported version of `react-native-firebase` for different React Native versions
| | v1 | [v2](https://github.com/invertase/react-native-firebase/pull/130)
| | v0.36 - v0.39 | v0.40 - v0.46 | v0.47 +
| ------------------------------- | :---: | :---: | :---: |
| react-native-firebase | 1.X.X | 2.X.X | 2.1.X |
> The table below shows the minimum supported versions of the Firebase SDKs for each version of `react-native-firebase`
| | v1 | v2 |
| ---------------------- | :---: | :---: |
| React Native | 0.36.0+ | 0.40.0 + |
| Firebase Android SDK | 10.2.0+ | 11.0.0 + |
| Firebase iOS SDK | 3.15.0+ | 4.0.0 + |

View File

@ -22,6 +22,7 @@
- [Performance Monitoring](/modules/perf)
- Other
- [Usage with Redux](/redux)
- [Project Board](https://github.com/invertase/react-native-firebase/projects)
- [FAQs / Troubleshooting](/faqs)
- [Examples](https://github.com/invertase/react-native-firebase-examples)

View File

@ -6,10 +6,10 @@ Currently due to the blackbox Firebase enviroment, we have found the best way to
For convenience all of the required NPM scripts are packaged with the main library to run the test app.
### Step 1 - Clone
### Step 1 - Fork & Clone
```bash
git clone git@github.com:invertase/react-native-firebase.git
git clone git@github.com:<username>/react-native-firebase.git
```
### Step 2 - Install dependencies
@ -53,3 +53,278 @@ npm run tests-pod-install
```
Open the `tests/ios/ReactNativeFirebaseDemo.xcworkspace` file in XCode and build for your preffered device or simulator.
## Tests
Tests are bootstrapped and ran when the `play` button is pressed. The status of each test suite and individual test will update as and when a test has completed or errored.
### Running tests
Tests can be run by pressing the play button in the toolbar of the app. Test can be run individually, by suite, or all at once.
![Test suite Android](https://github.com/invertase/react-native-firebase/blob/master/tests/docs/assets/test-suite-screenshot-android.png?raw=true)
### Adding test
To add tests to an existing test suite, you need to pass a function to `addTests`.
#### Synchronous tests
Synchronous tests are created by passing a function to `it`. The next test is run immediately after the last line is executed.
```javascript
testSuite.addTests(({ describe, it }) => {
describe('synchronous test', () => {
it('does something correctly', () => {
});
});
});
```
#### Asynchronous tests
Tests can be asynchronous if they return a promise. The test suite waits for the promise to resolve before executing the next test.
```javascript
testSuite.addTests(({ describe, it }) => {
describe('async successful test', () => {
it('does something correctly', () => {
return new Promise((resolve, reject) => {
// ...
resolve();
});
});
});
});
```
Asynchronous tests can also be created using the `async` function syntax:
```javascript
testSuite.addTests(({ describe, it }) => {
describe('async successful test', () => {
it('does something correctly', async () => {
// ...
await somethingAsynchronous();
});
});
});
```
> When rejecting, always ensure a valid [JavaScript Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) is provided.
### Creating a new test suite
A test suite groups together test categories under the same Firebase feature. e.g. *Realtime Database* tests.
To add a new test suite:
1. Create a new directory within `src/tests`.
2. Create an `index.js` file.
In this file, you need to create an instance of `TestSuite` - see [TestSuite constructor](#testsuite-constructor).
```javascript
import TestSuite from 'lib/TestSuite';
const MyNewSuite = new TestSuite('Realtime Database Storage', 'Upload/Download storage tests');
export default MyNewSuite;
```
3. `addTests` is then used as many times as is necessary to add tests to the test suite, accepting a function that defines one or more tests.
4. The test suite must then be imported into `src/tests/index.js` and added to `testSuiteInstances` in order for it to be included in the list of test suites available to run in the app.
## TestSuite API
### TestSuite Constructor
The TestSuite constructor accepts 3 arguments:
- **name**: String containing the name of the test suite. e.g. 'Realtime Storage'
- **description**: String containing description of the test suite
- **firebase**: This is the object exported from `src/firebase` and contains both the native and web firebase instances.
```javascript
import firebase from '../firebase';
new TestSuite('Realtime Database Storage', 'firebase.database()', firebase);
```
### Test Definition
#### describe()
The `describe()` function takes 2 - 3 arguments:
- **description**: String describing the context or target of all the tests defined in `testDefinitions`
- **options**: (Optional) object of options:
* **focus**: Boolean marking all the tests defined in `testDefinitions` (and any others marked as focused) as the only one(s) that should run
* **pending**: Boolean marking all the tests defined in `testDefinitions` as excluded from running in the test suite
- **testDefinitions**: Function that defines 1 or more tests by calling `it`, `xit` or `fit`
```javascript
function testCategory({ describe }) {
describe('a feature', () => {
it('does something synchronously', () => {
});
});
}
export default testCategory;
```
`describe()` statements can be arbitrarily nested.
#### context()
`context()` is an alias for `describe()` provided as syntactical sugar. `xcontext()` and `fcontext()` work similar to `xdescribe()` and `fdescribe()`, respectively.
#### it()
The `it()` function takes 2 - 3 arguments:
- **description**: String describing the test defined in `testDefinition`
- **options**: (Optional) object of options:
* **focus**: Boolean marking the test defined in `testDefinition` (and any others marked as focused) as the only one(s) that should run
* **pending**: Boolean marking the test defined in `testDefinition` as excluded from running in the test suite
* **timeout**: Time in milliseconds a test is allowed to execute before it's considered to have timed out. Default is 5000ms (5 seconds).
- **testDefinition**: Function that defines a test with one or more assertions. Can be a synchronous or asynchronous function. Functions that return a promise cause the test environment to wait for the promise to be resolved before proceding to the next test.
```javascript
it('does something synchronously', () => {
});
it('does something asynchronously', async () => {
});
it('does something else asynchronously', () => {
return new Promise(/* ... */);
});
```
`it()` statements can *not* be nested.
#### xdescribe() & xit()
##### Pending Tests
You can mark all tests within a `describe` statement as pending by using the `xdescribe` function instead. The test will appear greyed out and will not be run as part of the test suite.
You can mark a single test as pending by using `xit` as you would `it`.
Tests should only be marked as pending temporarily, and should not normally be committed to the test suite unless they are fully implemented.
#### fdescribe() & fit()
##### Focused Tests
You can mark all tests within a `describe` statement as focused by using the `fdescribe` function instead. Tests that are focused will be the only ones that appear and run in the test suite until all tests are removed from being focused. This is useful for running and working on a few tests at a time.
You can mark a single test as focused by using `fit` as you would `it`.
#### Test Assertions
The assertion library Should.js is used in the tests. The complete list of available assertions is available in the [Should.js documentation](https://shouldjs.github.io).
#### Lifecycle methods
Four lifecycle methods are provided for each test context:
- **before** - Run once, before the current test context executes
- **beforeEach** - Run before every test in the current test context
- **after** - Run once, after the current test context has finished executing
- **afterEach** - Run after every test in the current test context
A new test context is created when the test suite encounters any of `describe`, `xdescribe`, `fdescribe`, `context`, `xcontext` or `fcontext`, and close again when it reaches the end of the block. Test contexts can be nested and lifecycle hooks set for parent contexts apply for all descendents.
Each lifecycle hook accepts either a synchronous function, a function that returns a promise or an `async` function.
```javascript
function testCategory({ before, beforeEach, afterEach, after }) {
before(() => console.log('Before all tests start.'));
beforeEach(() => console.log('Before every test starts.'));
describe('sync successful test', function() {
// ...
});
afterEach(() => console.log('After each test starts.'));
after(() => console.log('After all tests are complete, with success or error.'));
}
```
An optional hash of options can also be passed as the first argument, defining one or more of the following values:
* **timeout**: Time in milliseconds a hook is allowed to execute before it's considered to have timed out. Default is 5000ms (5 seconds).
#### Accessing Firebase
`react-native-firebase` is available `firebase.native`:
```javascript
function testCategory({ describe, firebase }) {
describe('sync successful test', 'category', function() {
firebase.native.database();
});
}
```
If you need to access the web API for Firebase to compare with the functionality of `react-native-firebase`, you can access it on `firebase.web`.
> All tests should be written in terms of `react-native-firebase`'s behaviour and should **not** include direct comparisons with the web API. It's available for reference, only.
## Development Notes
> JavaScript changes do **not** require restarting the React Native packager to take effect
> Java changes will need to be rebuilt in Android Studio
> Objective-C changes need to be rebuilt in Xcode
### Debugging or viewing internals of the test suite
`react-native-firebase/tests` is compatible with [react-native-debugger](https://github.com/jhen0409/react-native-debugger) and is the recommended way to view the internal state of the test suite for development or troubleshooting.
It allows you to view state and prop values of the React component tree, view the actions and contents of the Redux store and view and interact with the debugging console.
Make sure **Remote JS Debugging** when running the application and close any chrome debugging windows that appear and start React Native Debugger.
### Running the internal tests
`react-native-firebase-tests` has its own tests to verify the testing framework is working as expected. These are run from the command line:
```bash
npm run internal-tests
```
## Troubleshooting
### Invalid React.podspec file: no implicit conversion of nil into String
This error occurs if you are using ruby version 2.1.2. Upgrade your version of ruby and try again.
### Unable to resolve module ../../../node_modules/react-native/packager/...
Run the packager separately, clearing the cache:
```bash
npm start -- --reset-cache
```

View File

@ -19,38 +19,6 @@ too large to manage on the existing repository, whilst trying to maintain backwa
RNFirebase was re-written from the ground up, addressing these issues with core focus being around matching the Web SDK as
closely as possible and fixing the major bugs/issues along the way.
## How do I integrate Redux with RNFirebase
As every project has different requirements & structure, RNFirebase *currently* has no built in methods for Redux integration.
As RNFirebase can be used outside of a Components context, you do have free reign to integrate it as you see fit. For example,
with [`redux-thunk`](https://github.com/gaearon/redux-thunk) you dispatch updates to your store with updates from Firebase:
```javascript
class MyApp extends React.Component {
componentDidMount() {
this.props.dispatch(onAuthStateChanged());
}
...
}
connect()(MyApp);
```
```javascript
export function onAuthStateChanged() {
return (dispatch) => {
firebase.auth().onAuthStateChanged((user) => {
dispatch({
type: 'AUTH_STATE_CHANGE',
user,
});
});
};
}
```
## [Android] Google Play Services related issues
The firebase SDK requires a certain version of Google Play Services installed on Android in order to function properly.

View File

@ -17,7 +17,7 @@
loadSidebar: true,
search: 'auto',
themeColor: '#f5820b',
subMaxLevel: 2,
subMaxLevel: 3,
maxLevel: 4,
ga: 'UA-98196653-1',
plugins: [

View File

@ -27,6 +27,39 @@ apply plugin: 'com.google.gms.google-services'
RNFirebase is split into separate modules to allow you to only include the Firebase functionality that you need in your application.
First add the project path to `android/settings.gradle`:
```
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
```
Now you need to include RNFirebase and the required Firebase dependencies in our `android/app/build.gradle` so that they are compiled as part of React Native. In the `dependencies` listing, add the appropriate `compile` lines:
```
dependencies {
// RNFirebase required dependencies
compile(project(':react-native-firebase')) {
transitive = false
}
compile "com.google.firebase:firebase-core:11.0.4"
// If you are receiving Google Play API availability issues, add the following dependency
compile "com.google.android.gms:play-services-base:11.0.4"
// RNFirebase optional dependencies
compile "com.google.firebase:firebase-ads:11.0.4"
compile "com.google.firebase:firebase-analytics:11.0.4"
compile "com.google.firebase:firebase-auth:11.0.4"
compile "com.google.firebase:firebase-config:11.0.4"
compile "com.google.firebase:firebase-crash:11.0.4"
compile "com.google.firebase:firebase-database:11.0.4"
compile "com.google.firebase:firebase-messaging:11.0.4"
compile "com.google.firebase:firebase-perf:11.0.4"
compile "com.google.firebase:firebase-storage:11.0.4"
}
```
To install `react-native-firebase` in your project, you'll need to import the packages you need from `io.invertase.firebase` in your project's `android/app/src/main/java/com/[app name]/MainApplication.java` and list them as packages for ReactNative in the `getPackages()` function:
```java
@ -42,7 +75,7 @@ import io.invertase.firebase.config.RNFirebaseRemoteConfigPackage; // Firebase R
import io.invertase.firebase.crash.RNFirebaseCrashPackage; // Firebase Crash Reporting
import io.invertase.firebase.database.RNFirebaseDatabasePackage; // Firebase Realtime Database
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // Firebase Cloud Messaging
import io.invertase.firebase.perf.RNFirebasePerformancePackage; // Firebase Messaging
import io.invertase.firebase.perf.RNFirebasePerformancePackage; // Firebase Performance
import io.invertase.firebase.storage.RNFirebaseStoragePackage; // Firebase Storage
// ...
public class MainApplication extends Application implements ReactApplication {
@ -69,35 +102,6 @@ public class MainApplication extends Application implements ReactApplication {
// ...
}
```
You'll also need to include RNFirebase and the required Firebase dependencies in our `android/app/build.gradle` so that they are compiled as part of React Native. In the `dependencies` listing, add the appropriate `compile` lines:
```
dependencies {
// RNFirebase Required dependencies
compile(project(':react-native-firebase')) {
transitive = false
}
compile "com.google.firebase:firebase-core:11.0.0"
// RNFirebase optional dependencies
compile "com.google.firebase:firebase-ads:11.0.0"
compile "com.google.firebase:firebase-analytics:11.0.0"
compile "com.google.firebase:firebase-auth:11.0.0"
compile "com.google.firebase:firebase-config:11.0.0"
compile "com.google.firebase:firebase-crash:11.0.0"
compile "com.google.firebase:firebase-database:11.0.0"
compile "com.google.firebase:firebase-messaging:11.0.0"
compile "com.google.firebase:firebase-perf:11.0.0"
compile "com.google.firebase:firebase-storage:11.0.0"
}
```
Add the project path to `android/settings.gradle`:
```
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
```
## 3) Cloud Messaging (optional)
@ -152,7 +156,7 @@ If you would like to schedule local notifications then you also need to add the
## 4) Performance Monitoring (optional)
If you'd like to take advantage of Firebases [Performance Monitoring](https://firebase.google.com/docs/perf-mon/), the following additions
If you'd like to take advantage of Firebase's [Performance Monitoring](https://firebase.google.com/docs/perf-mon/), the following additions
to your project setup are required:
In your projects `android/build.gradle` file, add the plugin to your dependencies:

View File

@ -1,5 +1,7 @@
# iOS Installation
Please note that there is a known issue when using Cocoapods with the `use_frameworks!` enabled. This is explained [here](https://github.com/invertase/react-native-firebase/issues/252#issuecomment-316340974). Unfortunately we don't currently have a workaround, but are engaging with Firebase directly to try and resolve the problem.
## 1) Setup GoogleService-Info.plist
Setup the `GoogleService-Info.plist` file by following the instructions and adding it to the root of your project at `ios/[YOUR APP NAME]/GoogleService-Info.plist` [here](https://firebase.google.com/docs/ios/setup#add_firebase_to_your_app).
@ -68,7 +70,7 @@ pod 'Firebase/RemoteConfig'
pod 'Firebase/Storage'
```
If you are new to Cocoapods or do not already have React installed as a pod, then add Yoga and React to your `Podfile` as follows:
If you do not already have React and Yoga installed as pods, then add Yoga and React to your `Podfile` as follows:
```ruby
pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
@ -141,6 +143,18 @@ Add the following methods:
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[RNFirebaseMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
[RNFirebaseMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler {
[RNFirebaseMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
```
### 3.5) Debugging

View File

@ -10,6 +10,8 @@ Badge notification is well known on the iOS platform, but also supported by diff
This library uses the [ShortcutBadger](https://github.com/leolin310148/ShortcutBadger) library to set the badge number
also on Android. A list of supported launcher can be found there.
!> [iOS] Please note: In order for iOS devices to receive Cloud Messages, ensure you [request permissions](http://invertase.io/react-native-firebase/#/modules/cloud-messaging?id=ios-requestpermissions).
## API
### subscribeToTopic(topic: string)

View File

@ -192,3 +192,13 @@ const ref = firebase.database
.child('roomId');
ref.keepSynced(true);
```
#### Security rules and offline persistence
Bear in mind that security rules live on the firebase server and **not in the client**. In other words, when offline, your app knows nothing about your database's security rules. This can lead to unexpected behaviour, which is explained in detail in the following blog post: https://firebase.googleblog.com/2016/11/what-happens-to-database-listeners-when-security-rules-reject-an-update.html
Some examples of behaviour you may not expect but may encounter are:
- Values that should not be readable, according to your security rules, are readable if they were created on the same device.
- Values are readable even when not authenticated, if they were created on the same device.
- Locations are writable even when they should not be, according to your security rules. This is more likely to cause unwanted behaviour when your app is offline, because when it is *online* the SDK will very quickly roll back the write once the server returns a permission error.

View File

@ -2,8 +2,8 @@
!> Performance monitoring requires react-native-firebase version 1.2.0.
?> If you plan on using this module in your own application, please ensure the optional setup instructions for
[Android](#) and [iOS](#) have been followed.
?> Android: If you plan on using this module in your own application, please ensure the optional setup instructions for
[Android](http://invertase.io/react-native-firebase/#/installation-android?id=_4-performance-monitoring-optional) have been followed.
Out of the box, [Firebase Performance Monitoring](https://firebase.google.com/docs/perf-mon/automatic) monitors a number of
[automatic traces](https://firebase.google.com/docs/perf-mon/automatic) such as app start/background/foreground response times.

View File

@ -1,8 +1,5 @@
# Transactions
!> Transactions is currently an experimental feature in RNFirebase. Whilst it does work there may still be some issues with it, especially around offline connectivity handling. Please report any issues in the usual manner.
?> For help on how to use firebase transactions please see the [Firebase Transaction Documentation](https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction).
### Android Implementation

125
docs/redux.md Normal file
View File

@ -0,0 +1,125 @@
# Usage with Redux
Although RNFirebase usage requires a React Native environment, it isn't tightly coupled which allows for full flexibility
when it comes to integrating with other modules such a [`react-redux`](https://github.com/reactjs/react-redux). If you wish to use
a Redux library designed for Firebase, we suggest taking a look at [`react-redux-firebase`](http://docs.react-redux-firebase.com/history/v2.0.0/docs/recipes/react-native.html)
for implementation with this module.
## Standalone integration
Although the following example works for a basic redux setup, it may differ when integrating with other redux middleware.
Imagine a simple TODO app, with redux we're able to abstract the Firebase logic out of components which allows for greater
testability and maintainability.
?> We use [`redux-thunk`](https://github.com/gaearon/redux-thunk) to provide async actions.
### Action Creators
```js
// Actions
export const subscribe = () => {
return (dispatch) => {
firebase.database().ref('todos').on('value', (snapshot) => {
const todos = [];
snapshot.forEach((childSnapshot) => {
todos.push({
id: childSnapshot.key,
...(childSnapshot.val()),
})
})
dispatch({
type: 'TODO_UPDATE',
todos,
})
})
}
}
// Methods
export const addTodo = text => {
firebase.database().ref('todos').push({
text,
visible: true,
})
}
export const completeTodo = id => {
firebase.database().ref(`todos/${id}`).update({
visible: false,
})
}
```
Instead of creating multiple actions which the reducers handle, we instead subscribe to the database ref and on any changes,
send a single action for the reducers to handle with the data which is constantly updating.
### Reducers
Our reducer now becomes really simple, as we're able to simply update the reducers state with whatever data has been returned
from our Firebase subscription.
```js
const todos = (state = {}, action) => {
switch (action.type) {
case 'TODO_UPDATE':
return { ...action.todos };
}
return state;
}
export default todos;
```
### Component
We can now easily subscribe to the todos in redux state and get live updates when Firebase updates.
```js
import React from 'react';
import { FlatList } from 'react-native';
import { connect } from 'react-redux';
import { subscribe, addTodo, completeTodo } from '../actions/TodoActions.js';
...
class Todos extends React.Component {
componentDidMount() {
this.props.dispatch(
subscribe()
);
}
onComplete = (id) => {
this.props.dispatch(
completeTodo(id)
);
};
onAdd = (text) => {
this.props.dispatch(
addTodo(text)
);
};
render() {
return (
<FlatList
data={this.props.todos}
...
/>
);
}
}
function mapStateToProps(state) {
return {
todos: state.todos,
};
}
export default connect(mapStateToProps)(Todos);
```

3
example/demo/.babelrc Normal file
View File

@ -0,0 +1,3 @@
{
"presets": ["react-native"]
}

6
example/demo/.buckconfig Normal file
View File

@ -0,0 +1,6 @@
[android]
target = Google Inc.:Google APIs:23
[maven_repositories]
central = https://repo1.maven.org/maven2

47
example/demo/.flowconfig Normal file
View File

@ -0,0 +1,47 @@
[ignore]
; We fork some components by platform
.*/*[.]android.js
; Ignore "BUCK" generated dirs
<PROJECT_ROOT>/\.buckd/
; Ignore unexpected extra "@providesModule"
.*/node_modules/.*/node_modules/fbjs/.*
; Ignore duplicate module providers
; For RN Apps installed via npm, "Libraries" folder is inside
; "node_modules/react-native" but in the source repo it is in the root
.*/Libraries/react-native/React.js
.*/Libraries/react-native/ReactNative.js
[include]
[libs]
node_modules/react-native/Libraries/react-native/react-native-interface.js
node_modules/react-native/flow
flow/
[options]
emoji=true
module.system=haste
experimental.strict_type_args=true
munge_underscores=true
module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'
suppress_type=$FlowIssue
suppress_type=$FlowFixMe
suppress_type=$FixMe
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(4[0-5]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(4[0-5]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
unsafe.enable_getters_and_setters=true
[version]
^0.45.0

1
example/demo/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
*.pbxproj -text

56
example/demo/.gitignore vendored Normal file
View File

@ -0,0 +1,56 @@
# OSX
#
.DS_Store
# Google
android/app/google-services.json
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
project.xcworkspace
# Android/IntelliJ
#
build/
.idea
.gradle
local.properties
*.iml
# node.js
#
node_modules/
npm-debug.log
yarn-error.log
# BUCK
buck-out/
\.buckd/
*.keystore
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots

View File

@ -0,0 +1 @@
{}

16
example/demo/README.md Normal file
View File

@ -0,0 +1,16 @@
### Description
This example project implements `react-native-firebase` as described in the
[installation instructions](http://invertase.io/react-native-firebase/#/initial-setup).
### Usage
1) Install node_modules: `$ yarn` or `$ npm install`
#### iOS
1) Go into ios root directory where the `Podfile` is located
2) Install pods: `$ pod install`
3) Run app: `$ react-native run-ios`
#### Android
1) Run app: `$ react-native run-android`

View File

@ -0,0 +1,65 @@
# To learn about Buck see [Docs](https://buckbuild.com/).
# To run your application with Buck:
# - install Buck
# - `npm start` - to start the packager
# - `cd android`
# - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
# - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
# - `buck install -r android/app` - compile, install and run application
#
lib_deps = []
for jarfile in glob(['libs/*.jar']):
name = 'jars__' + jarfile[jarfile.rindex('/') + 1: jarfile.rindex('.jar')]
lib_deps.append(':' + name)
prebuilt_jar(
name = name,
binary_jar = jarfile,
)
for aarfile in glob(['libs/*.aar']):
name = 'aars__' + aarfile[aarfile.rindex('/') + 1: aarfile.rindex('.aar')]
lib_deps.append(':' + name)
android_prebuilt_aar(
name = name,
aar = aarfile,
)
android_library(
name = "all-libs",
exported_deps = lib_deps,
)
android_library(
name = "app-code",
srcs = glob([
"src/main/java/**/*.java",
]),
deps = [
":all-libs",
":build_config",
":res",
],
)
android_build_config(
name = "build_config",
package = "com.demo",
)
android_resource(
name = "res",
package = "com.demo",
res = "src/main/res",
)
android_binary(
name = "app",
keystore = "//android/keystores:debug",
manifest = "src/main/AndroidManifest.xml",
package_type = "debug",
deps = [
":app-code",
],
)

View File

@ -0,0 +1,154 @@
apply plugin: "com.android.application"
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation
* entryFile: "index.android.js",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
apply from: "../../node_modules/react-native/react.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.demo"
minSdkVersion 16
targetSdkVersion 22
versionCode 1
versionName "1.0"
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86"
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = ["armeabi-v7a":1, "x86":2]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:23.0.1"
compile "com.google.android.gms:play-services-base:11.0.0"
compile "com.facebook.react:react-native:+" // From node_modules
compile(project(':react-native-firebase')) {
transitive = false
}
compile "com.google.firebase:firebase-core:11.0.0"
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply plugin: 'com.google.gms.google-services'

View File

@ -0,0 +1,42 @@
{
"project_info": {
"project_number": "305229645282",
"firebase_url": "https://rnfirebase-b9ad4.firebaseio.com",
"project_id": "rnfirebase-b9ad4",
"storage_bucket": "rnfirebase-b9ad4.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:305229645282:android:efe37851d57e1d05",
"android_client_info": {
"package_name": "com.demo"
}
},
"oauth_client": [
{
"client_id": "305229645282-j8ij0jev9ut24odmlk9i215pas808ugn.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCzbBYFyX8d6VdSu7T4s10IWYbPc-dguwM"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 1,
"other_platform_oauth_client": []
},
"ads_service": {
"status": 2
}
}
}
],
"configuration_version": "1"
}

View File

@ -0,0 +1,70 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Disabling obfuscation is useful if you collect stack traces from production crashes
# (unless you are using a system that supports de-obfuscate the stack traces).
-dontobfuscate
# React Native
# Keep our interfaces so they can be used by other ProGuard rules.
# See http://sourceforge.net/p/proguard/bugs/466/
-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters
-keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip
# Do not strip any method/class that is annotated with @DoNotStrip
-keep @com.facebook.proguard.annotations.DoNotStrip class *
-keep @com.facebook.common.internal.DoNotStrip class *
-keepclassmembers class * {
@com.facebook.proguard.annotations.DoNotStrip *;
@com.facebook.common.internal.DoNotStrip *;
}
-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
void set*(***);
*** get*();
}
-keep class * extends com.facebook.react.bridge.JavaScriptModule { *; }
-keep class * extends com.facebook.react.bridge.NativeModule { *; }
-keepclassmembers,includedescriptorclasses class * { native <methods>; }
-keepclassmembers class * { @com.facebook.react.uimanager.UIProp <fields>; }
-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }
-dontwarn com.facebook.react.**
# TextLayoutBuilder uses a non-public Android constructor within StaticLayout.
# See libs/proxy/src/main/java/com/facebook/fbui/textlayoutbuilder/proxy for details.
-dontwarn android.text.StaticLayout
# okhttp
-keepattributes Signature
-keepattributes *Annotation*
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
# okio
-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**

View File

@ -0,0 +1,32 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="22" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>

View File

@ -0,0 +1,15 @@
package com.demo;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "demo";
}
}

View File

@ -0,0 +1,43 @@
package com.demo;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import io.invertase.firebase.RNFirebasePackage;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">demo</string>
</resources>

View File

@ -0,0 +1,8 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
</resources>

View File

@ -0,0 +1,24 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
}
}

View File

@ -0,0 +1,20 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.useDeprecatedNdk=true

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

164
example/demo/android/gradlew vendored Executable file
View File

@ -0,0 +1,164 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
example/demo/android/gradlew.bat vendored Normal file
View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,8 @@
keystore(
name = "debug",
properties = "debug.keystore.properties",
store = "debug.keystore",
visibility = [
"PUBLIC",
],
)

View File

@ -0,0 +1,4 @@
key.store=debug.keystore
key.alias=androiddebugkey
key.store.password=android
key.alias.password=android

View File

@ -0,0 +1,4 @@
rootProject.name = 'demo'
include ':app'
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')

32
example/demo/app.js Normal file
View File

@ -0,0 +1,32 @@
import React from 'react';
import {
View,
Text,
StyleSheet
} from 'react-native';
import firebase from './lib/firebase';
export default class App extends React.Component {
render () {
return (
<View
style={styles.container}
>
<Text>
Successfully imported and running react-native-firebase.
</Text>
<Text>
Running app: {firebase.apps}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});

4
example/demo/app.json Normal file
View File

@ -0,0 +1,4 @@
{
"name": "demo",
"displayName": "demo"
}

View File

@ -0,0 +1,25 @@
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View
} from 'react-native';
import App from './app';
export default class demo extends Component {
render () {
return (
<View style={styles.container}>
<App />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
AppRegistry.registerComponent('demo', () => demo);

25
example/demo/index.ios.js Normal file
View File

@ -0,0 +1,25 @@
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View
} from 'react-native';
import App from './app';
export default class demo extends Component {
render () {
return (
<View style={styles.container}>
<App />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
AppRegistry.registerComponent('demo', () => demo);

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>AD_UNIT_ID_FOR_BANNER_TEST</key>
<string>ca-app-pub-3940256099942544/2934735716</string>
<key>AD_UNIT_ID_FOR_INTERSTITIAL_TEST</key>
<string>ca-app-pub-3940256099942544/4411468910</string>
<key>CLIENT_ID</key>
<string>305229645282-22imndi01abc2p6esgtu1i1m9mqrd0ib.apps.googleusercontent.com</string>
<key>REVERSED_CLIENT_ID</key>
<string>com.googleusercontent.apps.305229645282-22imndi01abc2p6esgtu1i1m9mqrd0ib</string>
<key>API_KEY</key>
<string>AIzaSyAcdVLG5dRzA1ck_fa_xd4Z0cY7cga7S5A</string>
<key>GCM_SENDER_ID</key>
<string>305229645282</string>
<key>PLIST_VERSION</key>
<string>1</string>
<key>BUNDLE_ID</key>
<string>com.demo</string>
<key>PROJECT_ID</key>
<string>rnfirebase-b9ad4</string>
<key>STORAGE_BUCKET</key>
<string>rnfirebase-b9ad4.appspot.com</string>
<key>IS_ADS_ENABLED</key>
<true/>
<key>IS_ANALYTICS_ENABLED</key>
<false/>
<key>IS_APPINVITE_ENABLED</key>
<false/>
<key>IS_GCM_ENABLED</key>
<true/>
<key>IS_SIGNIN_ENABLED</key>
<true/>
<key>GOOGLE_APP_ID</key>
<string>1:305229645282:ios:7b45748cb1117d2d</string>
<key>DATABASE_URL</key>
<string>https://rnfirebase-b9ad4.firebaseio.com</string>
</dict>
</plist>

37
example/demo/ios/Podfile Normal file
View File

@ -0,0 +1,37 @@
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'demo' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for demo
pod 'Firebase/Core'
pod 'RNFirebase', :path => '../node_modules/react-native-firebase'
pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'BatchedBridge', # Required For React Native 0.45.0+
'Core',
# Add any other subspecs you want to use in your project
]
target 'demoTests' do
inherit! :search_paths
# Pods for testing
end
end
target 'demo-tvOS' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for demo-tvOS
target 'demo-tvOSTests' do
inherit! :search_paths
# Pods for testing
end
end

View File

@ -0,0 +1,54 @@
PODS:
- Firebase/Core (4.0.3):
- FirebaseAnalytics (= 4.0.2)
- FirebaseCore (= 4.0.3)
- FirebaseAnalytics (4.0.2):
- FirebaseCore (~> 4.0)
- FirebaseInstanceID (~> 2.0)
- GoogleToolboxForMac/NSData+zlib (~> 2.1)
- FirebaseCore (4.0.3):
- GoogleToolboxForMac/NSData+zlib (~> 2.1)
- FirebaseInstanceID (2.0.0):
- FirebaseCore (~> 4.0)
- GoogleToolboxForMac/Defines (2.1.1)
- GoogleToolboxForMac/NSData+zlib (2.1.1):
- GoogleToolboxForMac/Defines (= 2.1.1)
- React/BatchedBridge (0.45.1):
- React/Core
- React/cxxreact_legacy
- React/Core (0.45.1):
- Yoga (= 0.45.1.React)
- React/cxxreact_legacy (0.45.1):
- React/jschelpers_legacy
- React/jschelpers_legacy (0.45.1)
- RNFirebase (2.0.1)
- Yoga (0.45.1.React)
DEPENDENCIES:
- Firebase/Core
- React/BatchedBridge (from `../node_modules/react-native`)
- React/Core (from `../node_modules/react-native`)
- RNFirebase (from `../node_modules/react-native-firebase`)
- Yoga (from `../node_modules/react-native/ReactCommon/yoga`)
EXTERNAL SOURCES:
React:
:path: "../node_modules/react-native"
RNFirebase:
:path: "../node_modules/react-native-firebase"
Yoga:
:path: "../node_modules/react-native/ReactCommon/yoga"
SPEC CHECKSUMS:
Firebase: 9e33fdfbca37cab635c693883caa90a4475b842b
FirebaseAnalytics: ad41720e3e67fc63fbe3d2948d3e26932a8de311
FirebaseCore: c709067051de07bdaffdc4e735cd7299a23c463a
FirebaseInstanceID: 9fbf536668f4d3f0880e7438456dabd1376e294b
GoogleToolboxForMac: 8e329f1b599f2512c6b10676d45736bcc2cbbeb0
React: 0c9191a8b0c843d7004f950ac6b5f6cba9d125c7
RNFirebase: 9d03ea6a3e877f59fb8835bf3e79571edd339451
Yoga: 89c8738d42a0b46a113acb4e574336d61cba2985
PODFILE CHECKSUM: 60be486e7b17438c067d4d9871e02042d2155726
COCOAPODS: 1.2.0.beta.3

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>NSAppTransportSecurity</key>
<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
</dict>
</plist>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0820"
version = "1.3">
<BuildAction
parallelizeBuildables = "NO"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D2A28121D9B038B00D4039D"
BuildableName = "libReact.a"
BlueprintName = "React-tvOS"
ReferencedContainer = "container:../node_modules/react-native/React/React.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "demo-tvOS.app"
BlueprintName = "demo-tvOS"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
BuildableName = "demo-tvOSTests.xctest"
BlueprintName = "demo-tvOSTests"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
BuildableName = "demo-tvOSTests.xctest"
BlueprintName = "demo-tvOSTests"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "demo-tvOS.app"
BlueprintName = "demo-tvOS"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "demo-tvOS.app"
BlueprintName = "demo-tvOS"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "demo-tvOS.app"
BlueprintName = "demo-tvOS"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0620"
version = "1.3">
<BuildAction
parallelizeBuildables = "NO"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "83CBBA2D1A601D0E00E9B192"
BuildableName = "libReact.a"
BlueprintName = "React"
ReferencedContainer = "container:../node_modules/react-native/React/React.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "demo.app"
BlueprintName = "demo"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
BuildableName = "demoTests.xctest"
BlueprintName = "demoTests"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
BuildableName = "demoTests.xctest"
BlueprintName = "demoTests"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "demo.app"
BlueprintName = "demo"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "demo.app"
BlueprintName = "demo"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "demo.app"
BlueprintName = "demo"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,16 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@end

View File

@ -0,0 +1,39 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <Firebase.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"demo"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[FIRApp configure];
return YES;
}
@end

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7702" systemVersion="14D136" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7701"/>
<capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB">
<rect key="frame" x="0.0" y="0.0" width="480" height="480"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Powered by React Native" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="8ie-xW-0ye">
<rect key="frame" x="20" y="439" width="441" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="demo" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX">
<rect key="frame" x="20" y="140" width="441" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="kId-c2-rCX" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="bottom" multiplier="1/3" constant="1" id="5cJ-9S-tgC"/>
<constraint firstAttribute="centerX" secondItem="kId-c2-rCX" secondAttribute="centerX" id="Koa-jz-hwk"/>
<constraint firstAttribute="bottom" secondItem="8ie-xW-0ye" secondAttribute="bottom" constant="20" id="Kzo-t9-V3l"/>
<constraint firstItem="8ie-xW-0ye" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="MfP-vx-nX0"/>
<constraint firstAttribute="centerX" secondItem="8ie-xW-0ye" secondAttribute="centerX" id="ZEH-qu-HZ9"/>
<constraint firstItem="kId-c2-rCX" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="fvb-Df-36g"/>
</constraints>
<nil key="simulatedStatusBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="548" y="455"/>
</view>
</objects>
</document>

View File

@ -0,0 +1,38 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>demo</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>NSAppTransportSecurity</key>
<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
</dict>
</plist>

View File

@ -0,0 +1,18 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

View File

@ -0,0 +1,70 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <React/RCTLog.h>
#import <React/RCTRootView.h>
#define TIMEOUT_SECONDS 600
#define TEXT_TO_LOOK_FOR @"Welcome to React Native!"
@interface demoTests : XCTestCase
@end
@implementation demoTests
- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test
{
if (test(view)) {
return YES;
}
for (UIView *subview in [view subviews]) {
if ([self findSubviewInView:subview matching:test]) {
return YES;
}
}
return NO;
}
- (void)testRendersWelcomeScreen
{
UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
BOOL foundElement = NO;
__block NSString *redboxError = nil;
RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
if (level >= RCTLogLevelError) {
redboxError = message;
}
});
while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
[[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
[[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) {
if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
return YES;
}
return NO;
}];
}
RCTSetLogFunction(RCTDefaultLogFunction);
XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
}
@end

View File

@ -0,0 +1,9 @@
import RNFirebase from 'react-native-firebase'
const configurationOptions = {
debug: true
}
const firebase = RNFirebase.initializeApp(configurationOptions)
export default firebase

23
example/demo/package.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "demo",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.0.0-alpha.12",
"react-native": "0.45.1",
"react-native-firebase": "^2.0.1"
},
"devDependencies": {
"babel-jest": "20.0.3",
"babel-preset-react-native": "2.0.0",
"jest": "20.0.4",
"react-test-renderer": "16.0.0-alpha.12"
},
"jest": {
"preset": "react-native"
}
}

124
index.d.ts vendored
View File

@ -7,21 +7,28 @@ declare module "react-native-firebase" {
export default class FireBase {
constructor(config?: RNFirebase.configurationOptions)
log: any
analytics(): RNFirebase.Analytics;
auth(): RNFirebase.auth.Auth;
on(type: string, handler: (msg: any) => void): any;
/** mimics firebase Web SDK */
/** mimics firebase Web SDK */
database: {
(): RNFirebase.database.Database
ServerValue: {
TIMESTAMP: number
}
}
/**RNFirebase mimics the Web Firebase SDK Storage,
* whilst providing some iOS and Android specific functionality.
*/
storage(): RNFirebase.storage.Storage;
/**
* Firebase Cloud Messaging (FCM) allows you to send push messages at no cost to both Android & iOS platforms.
* Assuming the installation instructions have been followed, FCM is ready to go.
@ -29,6 +36,7 @@ declare module "react-native-firebase" {
* the following methods within react-native-firebase have been created to handle FCM in the React Native environment.
*/
messaging(): RNFirebase.messaging.Messaging;
/**
* RNFirebase provides crash reporting for your app out of the box.
* Please note crashes do not appear in real-time on the console,
@ -37,9 +45,12 @@ declare module "react-native-firebase" {
* such as a pre-caught exception this is possible by using the report method.
*/
crash(): RNFirebase.crash.Crash;
apps: Array<string>;
googleApiAvailability: RNFirebase.GoogleApiAvailabilityType;
static initializeApp(options?: any | RNFirebase.configurationOptions, name?: string): FireBase;
[key: string]: any;
}
@ -56,10 +67,10 @@ declare module "react-native-firebase" {
};
/**
* pass custom options by passing an object with configuration options.
* The configuration object will be generated first by the native configuration object, if set and then will be overridden if passed in JS.
* That is, all of the following key/value pairs are optional if the native configuration is set.
*/
* pass custom options by passing an object with configuration options.
* The configuration object will be generated first by the native configuration object, if set and then will be overridden if passed in JS.
* That is, all of the following key/value pairs are optional if the native configuration is set.
*/
interface configurationOptions {
/**
* default false
@ -74,7 +85,7 @@ declare module "react-native-firebase" {
*/
persistence?: boolean;
/**
* Default from app [NSBundle mainBundle] The bundle ID for the app to be bundled with
* Default from app [NSBundle mainBundle] The bundle ID for the app to be bundled with
*/
bundleID?: string;
/**
@ -103,7 +114,7 @@ declare module "react-native-firebase" {
*/
androidClientID?: string;
/**
* default ""
* default ""
* The Project number from the Google Developer's console used to configure Google Cloud Messaging
*/
GCMSenderID?: string;
@ -127,12 +138,10 @@ declare module "react-native-firebase" {
namespace storage {
interface StorageTask<T> extends Promise<T> {
on(
event: TaskEvent,
nextOrObserver: (snapshot: any) => any,
error: (error: RnError) => any,
complete: (complete: any) => any
): any
on(event: TaskEvent,
nextOrObserver: (snapshot: any) => any,
error: (error: RnError) => any,
complete: (complete: any) => any): any
/**
* is not currently supported by react-native-firebase
*/
@ -183,17 +192,13 @@ declare module "react-native-firebase" {
name: string;
parent: storage.Reference | null;
put(data: any | Uint8Array | ArrayBuffer,
metadata?: storage.UploadMetadata):
storage.UploadTask;
putString(
data: string, format?: storage.StringFormat,
metadata?: storage.UploadMetadata):
storage.UploadTask;
metadata?: storage.UploadMetadata): storage.UploadTask;
putString(data: string, format?: storage.StringFormat,
metadata?: storage.UploadMetadata): storage.UploadTask;
root: storage.Reference;
storage: storage.Storage;
toString(): string;
updateMetadata(metadata: storage.SettableMetadata):
Promise<any>;
updateMetadata(metadata: storage.SettableMetadata): Promise<any>;
}
interface UploadMetadata extends storage.SettableMetadata {
md5Hash?: string | null;
@ -219,13 +224,12 @@ declare module "react-native-firebase" {
cancel(): boolean;
catch(onRejected: (a: RnError) => any): Promise<any>;
on(event: storage.TaskEvent, nextOrObserver?: null | Object,
error?: ((a: RnError) => any) | null, complete?: (() => any) | null): Function;
error?: ((a: RnError) => any) | null, complete?: (() => any) | null): Function;
pause(): boolean;
resume(): boolean;
snapshot: storage.UploadTaskSnapshot;
then(
onFulfilled?: ((a: storage.UploadTaskSnapshot) => any) | null,
onRejected?: ((a: RnError) => any) | null): Promise<any>;
then(onFulfilled?: ((a: storage.UploadTaskSnapshot) => any) | null,
onRejected?: ((a: RnError) => any) | null): Promise<any>;
}
interface UploadTaskSnapshot {
@ -310,18 +314,15 @@ declare module "react-native-firebase" {
limitToFirst(limit: number): database.Query;
limitToLast(limit: number): database.Query;
off(eventType?: string,
callback?: (a: database.DataSnapshot, b?: string | null) => any,
context?: Object | null): any;
callback?: (a: database.DataSnapshot, b?: string | null) => any,
context?: Object | null): any;
on(eventType: string,
callback: (a: database.DataSnapshot | null, b?: string) => any,
cancelCallbackOrContext?: Object | null, context?: Object | null):
(a: database.DataSnapshot | null, b?: string) => any;
once(
eventType: string,
successCallback?:
(a: database.DataSnapshot, b?: string) => any,
failureCallbackOrContext?: Object | null,
context?: Object | null): Promise<any>;
callback: (a: database.DataSnapshot | null, b?: string) => any,
cancelCallbackOrContext?: Object | null, context?: Object | null): (a: database.DataSnapshot | null, b?: string) => any;
once(eventType: string,
successCallback?: (a: database.DataSnapshot, b?: string) => any,
failureCallbackOrContext?: Object | null,
context?: Object | null): Promise<any>;
orderByChild(path: string): database.Query;
orderByKey(): database.Query;
orderByPriority(): database.Query;
@ -356,18 +357,14 @@ declare module "react-native-firebase" {
remove(onComplete?: (a: RnError | null) => any): Promise<any>;
root: database.Reference;
set(value: any, onComplete?: (a: RnError | null) => any): Promise<any>;
setPriority(
priority: string | number | null,
onComplete: (a: RnError | null) => any): Promise<any>;
setWithPriority(
newVal: any, newPriority: string | number | null,
onComplete?: (a: RnError | null) => any): Promise<any>;
transaction(
transactionUpdate: (a: any) => any,
onComplete?:
(a: RnError | null, b: boolean,
c: database.DataSnapshot | null) => any,
applyLocally?: boolean): Promise<any>;
setPriority(priority: string | number | null,
onComplete: (a: RnError | null) => any): Promise<any>;
setWithPriority(newVal: any, newPriority: string | number | null,
onComplete?: (a: RnError | null) => any): Promise<any>;
transaction(transactionUpdate: (a: any) => any,
onComplete?: (a: RnError | null, b: boolean,
c: database.DataSnapshot | null) => any,
applyLocally?: boolean): Promise<any>;
update(values: Object, onComplete?: (a: RnError | null) => any): Promise<any>;
}
}
@ -491,6 +488,17 @@ declare module "react-native-firebase" {
token: string,
secret: string
}
interface ActionCodeInfo {
email: string,
error: string,
fromEmail: string,
verifyEmail: string,
recoverEmail: string,
passwordReset: string
}
namespace auth {
interface Auth {
@ -507,9 +515,8 @@ declare module "react-native-firebase" {
* This method returns a unsubscribe function to stop listening to events.
* Always ensure you unsubscribe from the listener when no longer needed to prevent updates to components no longer in use.
*/
onAuthStateChanged(
nextOrObserver: Object, error?: (a: RnError) => any,
completed?: () => any): () => any;
onAuthStateChanged(nextOrObserver: Object, error?: (a: RnError) => any,
completed?: () => any): () => any;
/**
* We can create a user by calling the createUserWithEmailAndPassword() function.
* The method accepts two parameters, an email and a password.
@ -543,6 +550,21 @@ declare module "react-native-firebase" {
* the email will contain a password reset link rather than a code.
*/
sendPasswordResetEmail(email: string): Promise<void>
/**
* Completes the password reset process, given a confirmation code and new password.
*/
confirmPasswordReset(code: string, newPassword: string): Promise<any>
/**
* Applies a verification code sent to the user by email or other out-of-band mechanism.
*/
applyActionCode(code: string): Promise<any>
/**
* Checks a verification code sent to the user by email or other out-of-band mechanism.
*/
checkActionCode(code: string): Promise<ActionCodeInfo>
/**
* Completes the password reset process,
* given a confirmation code and new password.

View File

@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
8300A7DB1F3333F5001B16AB /* RNFirebaseDatabaseReference.m in Sources */ = {isa = PBXBuildFile; fileRef = 8300A7DA1F3333F5001B16AB /* RNFirebaseDatabaseReference.m */; };
839D916C1EF3E20B0077C7C8 /* RNFirebaseAdMob.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D914F1EF3E20A0077C7C8 /* RNFirebaseAdMob.m */; };
839D916D1EF3E20B0077C7C8 /* RNFirebaseAdMobInterstitial.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D91511EF3E20A0077C7C8 /* RNFirebaseAdMobInterstitial.m */; };
839D916E1EF3E20B0077C7C8 /* RNFirebaseAdMobRewardedVideo.m in Sources */ = {isa = PBXBuildFile; fileRef = 839D91531EF3E20A0077C7C8 /* RNFirebaseAdMobRewardedVideo.m */; };
@ -35,6 +36,8 @@
/* Begin PBXFileReference section */
134814201AA4EA6300B7C361 /* libRNFirebase.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRNFirebase.a; sourceTree = BUILT_PRODUCTS_DIR; };
8300A7D91F3333F5001B16AB /* RNFirebaseDatabaseReference.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseDatabaseReference.h; sourceTree = "<group>"; };
8300A7DA1F3333F5001B16AB /* RNFirebaseDatabaseReference.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNFirebaseDatabaseReference.m; sourceTree = "<group>"; };
839D914E1EF3E20A0077C7C8 /* RNFirebaseAdMob.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseAdMob.h; sourceTree = "<group>"; };
839D914F1EF3E20A0077C7C8 /* RNFirebaseAdMob.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNFirebaseAdMob.m; sourceTree = "<group>"; };
839D91501EF3E20A0077C7C8 /* RNFirebaseAdMobInterstitial.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNFirebaseAdMobInterstitial.h; sourceTree = "<group>"; };
@ -157,6 +160,8 @@
839D91601EF3E20A0077C7C8 /* database */ = {
isa = PBXGroup;
children = (
8300A7D91F3333F5001B16AB /* RNFirebaseDatabaseReference.h */,
8300A7DA1F3333F5001B16AB /* RNFirebaseDatabaseReference.m */,
839D91611EF3E20A0077C7C8 /* RNFirebaseDatabase.h */,
839D91621EF3E20A0077C7C8 /* RNFirebaseDatabase.m */,
);
@ -262,6 +267,7 @@
839D91741EF3E20B0077C7C8 /* RNFirebaseMessaging.m in Sources */,
839D91751EF3E20B0077C7C8 /* RNFirebasePerformance.m in Sources */,
839D916D1EF3E20B0077C7C8 /* RNFirebaseAdMobInterstitial.m in Sources */,
8300A7DB1F3333F5001B16AB /* RNFirebaseDatabaseReference.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};

View File

@ -1,5 +1,6 @@
#ifndef RNFirebase_h
#define RNFirebase_h
#import <Foundation/Foundation.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBridgeModule.h>

View File

@ -23,8 +23,7 @@
@end
#else
@interface NativeExpressComponent : NSObject {
}
@interface NativeExpressComponent : NSObject
@end
#endif

View File

@ -1,11 +1,11 @@
#ifndef RNFirebaseAdMob_h
#define RNFirebaseAdMob_h
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#if __has_include(<GoogleMobileAds/GADMobileAds.h>)
#import "Firebase.h"
#import "RNFirebaseEvents.h"
#import <React/RCTBridgeModule.h>
#import "React/RCTEventEmitter.h"
#import "GoogleMobileAds/GADInterstitialDelegate.h"
#import "GoogleMobileAds/GADRewardBasedVideoAdDelegate.h"
@ -23,8 +23,7 @@
@end
#else
@interface RNFirebaseAdMob : NSObject {
}
@interface RNFirebaseAdMob : NSObject
@end
#endif

View File

@ -2,8 +2,6 @@
#if __has_include(<GoogleMobileAds/GADMobileAds.h>)
#import "GoogleMobileAds/GADMobileAds.h"
#import "RNFirebaseAdMobInterstitial.h"
#import "RNFirebaseAdMobRewardedVideo.h"
@ -35,7 +33,7 @@ RCT_EXPORT_METHOD(initialize:
RCT_EXPORT_METHOD(openDebugMenu:
(NSString *) appId) {
GADDebugOptionsViewController *debugOptionsViewController = [GADDebugOptionsViewController debugOptionsViewControllerWithAdUnitID:appId];
UIWindow* window = [UIApplication sharedApplication].keyWindow;
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[[window rootViewController] presentViewController:debugOptionsViewController animated:YES completion:nil];
}
@ -68,6 +66,11 @@ RCT_EXPORT_METHOD(rewardedVideoShowAd:
[rewardedVideo show];
}
RCT_EXPORT_METHOD(clearInterstitial:
(NSString *) adUnit) {
if (_interstitials[adUnit]) [_interstitials removeObjectForKey:adUnit];
}
- (RNFirebaseAdMobInterstitial *)getOrCreateInterstitial:(NSString *)adUnit {
if (_interstitials[adUnit]) {
return _interstitials[adUnit];
@ -187,8 +190,8 @@ RCT_EXPORT_METHOD(rewardedVideoShowAd:
NSString *matchText = [value substringWithRange:[match range]];
if (matchText) {
NSArray *values = [matchText componentsSeparatedByString:@"x"];
CGFloat width = (CGFloat)[values[0] intValue];
CGFloat height = (CGFloat)[values[1] intValue];
CGFloat width = (CGFloat) [values[0] intValue];
CGFloat height = (CGFloat) [values[1] intValue];
return GADAdSizeFromCGSize(CGSizeMake(width, height));
}
}
@ -216,8 +219,7 @@ RCT_EXPORT_METHOD(rewardedVideoShowAd:
#else
@interface RNFirebaseAdMobRewardedVideo : NSObject <RCTBridgeModule> {
}
@implementation RNFirebaseAdMob
@end
#endif
#endif

View File

@ -1,6 +1,8 @@
#ifndef RNFirebaseAnalytics_h
#define RNFirebaseAnalytics_h
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseAnalytics/FIRAnalytics.h>)
#import <React/RCTBridgeModule.h>
@interface RNFirebaseAnalytics : NSObject <RCTBridgeModule> {
@ -9,4 +11,9 @@
@end
#else
@interface RNFirebaseAnalytics : NSObject
@end
#endif
#endif

View File

@ -1,10 +1,10 @@
#ifndef RNFirebaseAuth_h
#define RNFirebaseAuth_h
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseAuth/FIRAuth.h>)
#import "Firebase.h"
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface RNFirebaseAuth : RCTEventEmitter <RCTBridgeModule> {
@ -15,8 +15,7 @@
@end
#else
@interface RNFirebaseAuth : NSObject <RCTBridgeModule> {
}
@interface RNFirebaseAuth : NSObject
@end
#endif

View File

@ -321,6 +321,83 @@ RCT_EXPORT_METHOD(signInWithCredential:(NSString *)provider token:(NSString *)au
}];
}
/**
confirmPasswordReset
@param NSString code
@param NSString newPassword
@param RCTPromiseResolveBlock resolve
@param RCTPromiseRejectBlock reject
@return
*/
RCT_EXPORT_METHOD(confirmPasswordReset:(NSString *)code newPassword:(NSString *)newPassword resolver:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject) {
[[FIRAuth auth] confirmPasswordResetWithCode:code newPassword:newPassword completion:^(NSError *_Nullable error) {
if (error) {
[self promiseRejectAuthException:reject error:error];
} else {
[self promiseNoUser:resolve rejecter:reject isError:NO];
}
}];
}
/**
* applyActionCode
*
* @param NSString code
* @param RCTPromiseResolveBlock resolve
* @param RCTPromiseRejectBlock reject
* @return
*/
RCT_EXPORT_METHOD(applyActionCode:(NSString *)code resolver:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject) {
[[FIRAuth auth] applyActionCode:code completion:^(NSError *_Nullable error) {
if (error) {
[self promiseRejectAuthException:reject error:error];
} else {
[self promiseNoUser:resolve rejecter:reject isError:NO];
}
}];
}
/**
* checkActionCode
*
* @param NSString code
* @param RCTPromiseResolveBlock resolve
* @param RCTPromiseRejectBlock reject
* @return
*/
RCT_EXPORT_METHOD(checkActionCode:(NSString *) code resolver:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject) {
[[FIRAuth auth] checkActionCode:code completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error){
if (error) {
[self promiseRejectAuthException:reject error:error];
} else {
NSString *actionType = @"ERROR";
switch (info.operation) {
case FIRActionCodeOperationPasswordReset:
actionType = @"PASSWORD_RESET";
break;
case FIRActionCodeOperationVerifyEmail:
actionType = @"VERIFY_EMAIL";
break;
case FIRActionCodeOperationUnknown:
actionType = @"UNKNOWN";
break;
}
NSDictionary * result = @{
@"data": @{
@"email": [info dataForKey:FIRActionCodeEmailKey],
@"fromEmail": [info dataForKey:FIRActionCodeFromEmailKey],
},
@"actionType": actionType,
};
resolve(result);
}
}];
}
/**
sendPasswordResetEmail
@ -401,6 +478,32 @@ RCT_EXPORT_METHOD(link:(NSString *)provider authToken:(NSString *)authToken auth
}
}
/**
unlink
@param NSString provider
@param NSString authToken
@param NSString authSecret
@param RCTPromiseResolveBlock resolve
@param RCTPromiseRejectBlock reject
@return
*/
RCT_EXPORT_METHOD(unlink:(NSString *)providerId resolver:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject) {
FIRUser *user = [FIRAuth auth].currentUser;
if (user) {
[user unlinkFromProvider:providerId completion:^(FIRUser *_Nullable _user, NSError *_Nullable error) {
if (error) {
[self promiseRejectAuthException:reject error:error];
} else {
[self promiseWithUser:resolve rejecter:reject user:_user];
}
}];
} else {
[self promiseNoUser:resolve rejecter:reject isError:YES];
}
}
/**
reauthenticate

View File

@ -1,10 +1,17 @@
#ifndef RNFirebaseRemoteConfig_h
#define RNFirebaseRemoteConfig_h
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseRemoteConfig/FirebaseRemoteConfig.h>)
#import <React/RCTBridgeModule.h>
@interface RNFirebaseRemoteConfig : NSObject <RCTBridgeModule>
@end
#else
@interface RNFirebaseRemoteConfig : NSObject
@end
#endif
#endif

View File

@ -3,14 +3,15 @@
#if __has_include(<FirebaseRemoteConfig/FirebaseRemoteConfig.h>)
#import "FirebaseRemoteConfig/FirebaseRemoteConfig.h"
#import <React/RCTConvert.h>
#import <React/RCTUtils.h>
NSString *convertFIRRemoteConfigFetchStatusToNSString(FIRRemoteConfigFetchStatus value)
{
switch(value){
case FIRRemoteConfigFetchStatusNoFetchYet:
return @"config/no_fetch_yet";
case FIRRemoteConfigFetchStatusFailure:
return @"config/failure";
case FIRRemoteConfigFetchStatusSuccess:
return @"config/success";
case FIRRemoteConfigFetchStatusThrottled:
return @"config/throttled";
default:

View File

@ -1,6 +1,8 @@
#ifndef RNFirebaseCrash_h
#define RNFirebaseCrash_h
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseCrash/FIRCrashLog.h>)
#import <React/RCTBridgeModule.h>
@interface RNFirebaseCrash : NSObject <RCTBridgeModule> {
@ -9,4 +11,9 @@
@end
#else
@interface RNFirebaseCrash : NSObject
@end
#endif
#endif

View File

@ -1,9 +1,9 @@
#ifndef RNFirebaseDatabase_h
#define RNFirebaseDatabase_h
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseDatabase/FIRDatabase.h>)
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface RNFirebaseDatabase : RCTEventEmitter<RCTBridgeModule> {}
@ -13,7 +13,7 @@
@end
#else
@interface RNFirebaseDatabase : NSObject<RCTBridgeModule> {}
@interface RNFirebaseDatabase : NSObject
@end
#endif

View File

@ -1,217 +1,9 @@
#import "RNFirebaseDatabase.h"
#import "RNFirebaseEvents.h"
#import "Firebase.h"
#if __has_include(<FirebaseDatabase/FIRDatabase.h>)
@interface RNFirebaseDBReference : NSObject
@property RCTEventEmitter *emitter;
@property FIRDatabaseQuery *query;
@property NSNumber *refId;
@property NSString *path;
@property NSMutableDictionary *listeners;
+ (NSDictionary *)snapshotToDict:(FIRDataSnapshot *)snapshot;
@end
@implementation RNFirebaseDBReference
- (id)initWithPathAndModifiers:(RCTEventEmitter *)emitter database:(FIRDatabase *)database refId:(NSNumber *)refId path:(NSString *)path modifiers:(NSArray *)modifiers {
self = [super init];
if (self) {
_emitter = emitter;
_refId = refId;
_path = path;
_query = [self buildQueryAtPathWithModifiers:database path:path modifiers:modifiers];
_listeners = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)addEventHandler:(NSNumber *)listenerId eventName:(NSString *)eventName {
if (!_listeners[listenerId]) {
id andPreviousSiblingKeyWithBlock = ^(FIRDataSnapshot *_Nonnull snapshot, NSString *_Nullable previousChildName) {
NSDictionary *props = [RNFirebaseDBReference snapshotToDict:snapshot];
[self sendJSEvent:DATABASE_DATA_EVENT title:eventName props:@{
@"eventName": eventName,
@"refId": _refId,
@"listenerId": listenerId,
@"path": _path,
@"snapshot": props,
@"previousChildName": previousChildName != nil ? previousChildName : [NSNull null]
}];
};
id errorBlock = ^(NSError *_Nonnull error) {
NSLog(@"Error onDBEvent: %@", [error debugDescription]);
[self removeEventHandler:listenerId eventName:eventName];
[self getAndSendDatabaseError:error listenerId:listenerId];
};
int eventType = [self eventTypeFromName:eventName];
FIRDatabaseHandle handle = [_query observeEventType:eventType andPreviousSiblingKeyWithBlock:andPreviousSiblingKeyWithBlock withCancelBlock:errorBlock];
_listeners[listenerId] = @(handle);
} else {
NSLog(@"Warning Trying to add duplicate listener for refId: %@ listenerId: %@", _refId, listenerId);
}
}
- (void)addSingleEventHandler:(RCTResponseSenderBlock)callback {
[_query observeSingleEventOfType:FIRDataEventTypeValue andPreviousSiblingKeyWithBlock:^(FIRDataSnapshot *_Nonnull snapshot, NSString *_Nullable previousChildName) {
NSDictionary *props = [RNFirebaseDBReference snapshotToDict:snapshot];
callback(@[[NSNull null], @{
@"eventName": @"value",
@"path": _path,
@"refId": _refId,
@"snapshot": props,
@"previousChildName": previousChildName != nil ? previousChildName : [NSNull null]
}]);
} withCancelBlock:^(NSError *_Nonnull error) {
NSLog(@"Error onDBEventOnce: %@", [error debugDescription]);
callback(@[@{@"eventName": DATABASE_ERROR_EVENT, @"path": _path, @"refId": _refId, @"code": @([error code]), @"details": [error debugDescription], @"message": [error localizedDescription], @"description": [error description]}]);
}];
}
- (void)removeEventHandler:(NSNumber *)listenerId eventName:(NSString *)eventName {
FIRDatabaseHandle handle = (FIRDatabaseHandle) [_listeners[listenerId] integerValue];
if (handle) {
[_listeners removeObjectForKey:listenerId];
[_query removeObserverWithHandle:handle];
}
}
+ (NSDictionary *)snapshotToDict:(FIRDataSnapshot *)snapshot {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:snapshot.key forKey:@"key"];
NSDictionary *val = snapshot.value;
dict[@"value"] = val;
// Snapshot ordering
NSMutableArray *childKeys = [NSMutableArray array];
if (snapshot.childrenCount > 0) {
// Since JS does not respect object ordering of keys
// we keep a list of the keys and their ordering
// in the snapshot event
NSEnumerator *children = [snapshot children];
FIRDataSnapshot *child;
while (child = [children nextObject]) {
[childKeys addObject:child.key];
}
}
dict[@"childKeys"] = childKeys;
[dict setValue:@(snapshot.hasChildren) forKey:@"hasChildren"];
[dict setValue:@(snapshot.exists) forKey:@"exists"];
[dict setValue:@(snapshot.childrenCount) forKey:@"childrenCount"];
[dict setValue:snapshot.priority forKey:@"priority"];
return dict;
}
- (NSDictionary *)getAndSendDatabaseError:(NSError *)error listenerId:(NSNumber *)listenerId {
NSDictionary *event = @{@"eventName": DATABASE_ERROR_EVENT, @"path": _path, @"refId": _refId, @"listenerId": listenerId, @"code": @([error code]), @"details": [error debugDescription], @"message": [error localizedDescription], @"description": [error description]};
@try {
[_emitter sendEventWithName:DATABASE_ERROR_EVENT body:event];
} @catch (NSException *err) {
NSLog(@"An error occurred in getAndSendDatabaseError: %@", [err debugDescription]);
NSLog(@"Tried to send: %@ with %@", DATABASE_ERROR_EVENT, event);
}
return event;
}
- (void)sendJSEvent:(NSString *)type title:(NSString *)title props:(NSDictionary *)props {
@try {
[_emitter sendEventWithName:type body:@{@"eventName": title, @"body": props}];
} @catch (NSException *err) {
NSLog(@"An error occurred in sendJSEvent: %@", [err debugDescription]);
NSLog(@"Tried to send: %@ with %@", title, props);
}
}
- (FIRDatabaseQuery *)buildQueryAtPathWithModifiers:(FIRDatabase *)database path:(NSString *)path modifiers:(NSArray *)modifiers {
FIRDatabaseQuery *query = [[database reference] child:path];
for (NSDictionary *modifier in modifiers) {
NSString *type = [modifier valueForKey:@"type"];
NSString *name = [modifier valueForKey:@"name"];
if ([type isEqualToString:@"orderBy"]) {
if ([name isEqualToString:@"orderByKey"]) {
query = [query queryOrderedByKey];
} else if ([name isEqualToString:@"orderByPriority"]) {
query = [query queryOrderedByPriority];
} else if ([name isEqualToString:@"orderByValue"]) {
query = [query queryOrderedByValue];
} else if ([name isEqualToString:@"orderByChild"]) {
NSString *key = [modifier valueForKey:@"key"];
query = [query queryOrderedByChild:key];
}
} else if ([type isEqualToString:@"limit"]) {
int limit = [[modifier valueForKey:@"limit"] integerValue];
if ([name isEqualToString:@"limitToLast"]) {
query = [query queryLimitedToLast:limit];
} else if ([name isEqualToString:@"limitToFirst"]) {
query = [query queryLimitedToFirst:limit];
}
} else if ([type isEqualToString:@"filter"]) {
NSString *valueType = [modifier valueForKey:@"valueType"];
NSString *key = [modifier valueForKey:@"key"];
id value = [self getIdValue:[modifier valueForKey:@"value"] type:valueType];
if ([name isEqualToString:@"equalTo"]) {
if (key != nil) {
query = [query queryEqualToValue:value childKey:key];
} else {
query = [query queryEqualToValue:value];
}
} else if ([name isEqualToString:@"endAt"]) {
if (key != nil) {
query = [query queryEndingAtValue:value childKey:key];
} else {
query = [query queryEndingAtValue:value];
}
} else if ([name isEqualToString:@"startAt"]) {
if (key != nil) {
query = [query queryStartingAtValue:value childKey:key];
} else {
query = [query queryStartingAtValue:value];
}
}
}
}
return query;
}
- (id)getIdValue:(NSString *)value type:(NSString *)type {
if ([type isEqualToString:@"number"]) {
return @(value.doubleValue);
} else if ([type isEqualToString:@"boolean"]) {
return @(value.boolValue);
} else {
return value;
}
}
- (BOOL)hasListeners {
return [[_listeners allKeys] count] > 0;
}
- (int)eventTypeFromName:(NSString *)name {
int eventType = FIRDataEventTypeValue;
if ([name isEqualToString:DATABASE_VALUE_EVENT]) {
eventType = FIRDataEventTypeValue;
} else if ([name isEqualToString:DATABASE_CHILD_ADDED_EVENT]) {
eventType = FIRDataEventTypeChildAdded;
} else if ([name isEqualToString:DATABASE_CHILD_MODIFIED_EVENT]) {
eventType = FIRDataEventTypeChildChanged;
} else if ([name isEqualToString:DATABASE_CHILD_REMOVED_EVENT]) {
eventType = FIRDataEventTypeChildRemoved;
} else if ([name isEqualToString:DATABASE_CHILD_MOVED_EVENT]) {
eventType = FIRDataEventTypeChildMoved;
}
return eventType;
}
@end
#import "RNFirebaseDatabaseReference.h"
#import "RNFirebaseEvents.h"
#import "Firebase.h"
@implementation RNFirebaseDatabase
RCT_EXPORT_MODULE();
@ -280,7 +72,7 @@ RCT_EXPORT_METHOD(startTransaction:
if (databaseError != nil) {
[self sendTransactionEvent:DATABASE_TRANSACTION_EVENT body:@{@"id": identifier, @"type": @"error", @"code": @([databaseError code]), @"message": [databaseError description]}];
} else {
[self sendTransactionEvent:DATABASE_TRANSACTION_EVENT body:@{@"id": identifier, @"type": @"complete", @"committed": @(committed), @"snapshot": [RNFirebaseDBReference snapshotToDict:snapshot],}];
[self sendTransactionEvent:DATABASE_TRANSACTION_EVENT body:@{@"id": identifier, @"type": @"complete", @"committed": @(committed), @"snapshot": [RNFirebaseDatabaseReference snapshotToDict:snapshot],}];
}
}
withLocalEvents:
@ -356,6 +148,25 @@ RCT_EXPORT_METHOD(set:
}];
}
RCT_EXPORT_METHOD(priority:(NSString *) path
priorityData:(NSDictionary *) priorityData
callback:(RCTResponseSenderBlock) callback) {
FIRDatabaseReference *ref = [self getPathRef:path];
[ref setPriority:[priorityData valueForKey:@"value"] withCompletionBlock:^(NSError * _Nullable error, FIRDatabaseReference * _Nonnull ref) {
[self handleCallback:@"priority" callback:callback databaseError:error];
}];
}
RCT_EXPORT_METHOD(withPriority:(NSString *) path
data:(NSDictionary *) data
priorityData:(NSDictionary *) priorityData
callback:(RCTResponseSenderBlock) callback) {
FIRDatabaseReference *ref = [self getPathRef:path];
[ref setValue:[data valueForKey:@"value"] andPriority:[priorityData valueForKey:@"value"] withCompletionBlock:^(NSError * _Nullable error, FIRDatabaseReference * _Nonnull ref) {
[self handleCallback:@"withPriority" callback:callback databaseError:error];
}];
}
RCT_EXPORT_METHOD(update:
(NSString *) path
value:
@ -415,7 +226,7 @@ RCT_EXPORT_METHOD(on:
listenerId:(nonnull NSNumber *) listenerId
name:(NSString *) eventName
callback:(RCTResponseSenderBlock) callback) {
RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
RNFirebaseDatabaseReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
[ref addEventHandler:listenerId eventName:eventName];
callback(@[[NSNull null], @{@"status": @"success", @"refId": refId, @"handle": path}]);
}
@ -427,8 +238,8 @@ RCT_EXPORT_METHOD(once:
modifiers:(NSArray *) modifiers
eventName:(NSString *) eventName
callback:(RCTResponseSenderBlock) callback) {
RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
[ref addSingleEventHandler:callback];
RNFirebaseDatabaseReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
[ref addSingleEventHandler:eventName callback:callback];
}
RCT_EXPORT_METHOD(off:
@ -436,7 +247,7 @@ RCT_EXPORT_METHOD(off:
NSNumber *) refId
listeners:(NSArray *) listeners
callback:(RCTResponseSenderBlock) callback) {
RNFirebaseDBReference *ref = _dbReferences[refId];
RNFirebaseDatabaseReference *ref = _dbReferences[refId];
if (ref != nil) {
for (NSDictionary *listener in listeners) {
NSNumber *listenerId = [listener valueForKey:@"listenerId"];
@ -459,8 +270,8 @@ RCT_EXPORT_METHOD(onDisconnectSet:
(RCTResponseSenderBlock) callback) {
FIRDatabaseReference *ref = [self getPathRef:path];
[ref onDisconnectSetValue:props[@"value"] withCompletionBlock:^(NSError *_Nullable error, FIRDatabaseReference *_Nonnull _ref) {
[self handleCallback:@"onDisconnectSetObject" callback:callback databaseError:error];
}];
[self handleCallback:@"onDisconnectSetObject" callback:callback databaseError:error];
}];
}
RCT_EXPORT_METHOD(onDisconnectRemove:
@ -505,11 +316,11 @@ RCT_EXPORT_METHOD(goOnline) {
}
}
- (RNFirebaseDBReference *)getDBHandle:(NSNumber *)refId path:(NSString *)path modifiers:(NSArray *)modifiers {
RNFirebaseDBReference *ref = _dbReferences[refId];
- (RNFirebaseDatabaseReference *)getDBHandle:(NSNumber *)refId path:(NSString *)path modifiers:(NSArray *)modifiers {
RNFirebaseDatabaseReference *ref = _dbReferences[refId];
if (ref == nil) {
ref = [[RNFirebaseDBReference alloc] initWithPathAndModifiers:self database:[FIRDatabase database] refId:refId path:path modifiers:modifiers];
ref = [[RNFirebaseDatabaseReference alloc] initWithPathAndModifiers:self database:[FIRDatabase database] refId:refId path:path modifiers:modifiers];
_dbReferences[refId] = ref;
}
return ref;

View File

@ -0,0 +1,31 @@
#ifndef RNFirebaseDatabaseReference_h
#define RNFirebaseDatabaseReference_h
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseDatabase/FIRDatabase.h>)
#import "RNFirebaseEvents.h"
#import <React/RCTEventEmitter.h>
#import "Firebase.h"
@interface RNFirebaseDatabaseReference : NSObject
@property RCTEventEmitter *emitter;
@property FIRDatabaseQuery *query;
@property NSNumber *refId;
@property NSString *path;
@property NSMutableDictionary *listeners;
- (id)initWithPathAndModifiers:(RCTEventEmitter *)emitter database:(FIRDatabase *)database refId:(NSNumber *)refId path:(NSString *)path modifiers:(NSArray *)modifiers;
- (void)addEventHandler:(NSNumber *)listenerId eventName:(NSString *)eventName;
- (void)addSingleEventHandler:(NSString *)eventName callback:(RCTResponseSenderBlock)callback;
- (void)removeEventHandler:(NSNumber *)listenerId eventName:(NSString *)eventName;
- (BOOL)hasListeners;
+ (NSDictionary *)snapshotToDict:(FIRDataSnapshot *)snapshot;
@end
#else
@interface RNFirebaseDatabaseReference : NSObject
@end
#endif
#endif

View File

@ -0,0 +1,191 @@
#import "RNFirebaseDatabaseReference.h"
@implementation RNFirebaseDatabaseReference
#if __has_include(<FirebaseDatabase/FIRDatabase.h>)
- (id)initWithPathAndModifiers:(RCTEventEmitter *)emitter database:(FIRDatabase *)database refId:(NSNumber *)refId path:(NSString *)path modifiers:(NSArray *)modifiers {
self = [super init];
if (self) {
_emitter = emitter;
_refId = refId;
_path = path;
_query = [self buildQueryAtPathWithModifiers:database path:path modifiers:modifiers];
_listeners = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)addEventHandler:(NSNumber *)listenerId eventName:(NSString *)eventName {
if (!_listeners[listenerId]) {
id andPreviousSiblingKeyWithBlock = ^(FIRDataSnapshot *_Nonnull snapshot, NSString *_Nullable previousChildName) {
NSDictionary *props = [RNFirebaseDatabaseReference snapshotToDict:snapshot];
[self sendJSEvent:DATABASE_DATA_EVENT title:eventName props:@{@"eventName": eventName, @"refId": _refId, @"listenerId": listenerId, @"path": _path, @"snapshot": props, @"previousChildName": previousChildName != nil ? previousChildName : [NSNull null]}];
};
id errorBlock = ^(NSError *_Nonnull error) {
NSLog(@"Error onDBEvent: %@", [error debugDescription]);
[self removeEventHandler:listenerId eventName:eventName];
[self getAndSendDatabaseError:error listenerId:listenerId];
};
int eventType = [self eventTypeFromName:eventName];
FIRDatabaseHandle handle = [_query observeEventType:eventType andPreviousSiblingKeyWithBlock:andPreviousSiblingKeyWithBlock withCancelBlock:errorBlock];
_listeners[listenerId] = @(handle);
} else {
NSLog(@"Warning Trying to add duplicate listener for refId: %@ listenerId: %@", _refId, listenerId);
}
}
- (void)addSingleEventHandler:(NSString *)eventName callback:(RCTResponseSenderBlock)callback {
FIRDataEventType firDataEventType = (FIRDataEventType)[self eventTypeFromName:eventName];
[_query observeSingleEventOfType:firDataEventType andPreviousSiblingKeyWithBlock:^(FIRDataSnapshot *_Nonnull snapshot, NSString *_Nullable previousChildName) {
NSDictionary *props = [RNFirebaseDatabaseReference snapshotToDict:snapshot];
callback(@[[NSNull null], @{@"eventName": eventName, @"path": _path, @"refId": _refId, @"snapshot": props, @"previousChildName": previousChildName != nil ? previousChildName : [NSNull null]}]);
} withCancelBlock:^(NSError *_Nonnull error) {
NSLog(@"Error onDBEventOnce: %@", [error debugDescription]);
callback(@[@{@"eventName": DATABASE_ERROR_EVENT, @"path": _path, @"refId": _refId, @"code": @([error code]), @"details": [error debugDescription], @"message": [error localizedDescription], @"description": [error description]}]);
}];
}
- (void)removeEventHandler:(NSNumber *)listenerId eventName:(NSString *)eventName {
FIRDatabaseHandle handle = (FIRDatabaseHandle) [_listeners[listenerId] integerValue];
if (handle) {
[_listeners removeObjectForKey:listenerId];
[_query removeObserverWithHandle:handle];
}
}
+ (NSDictionary *)snapshotToDict:(FIRDataSnapshot *)snapshot {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:snapshot.key forKey:@"key"];
NSDictionary *val = snapshot.value;
dict[@"value"] = val;
// Snapshot ordering
NSMutableArray *childKeys = [NSMutableArray array];
if (snapshot.childrenCount > 0) {
// Since JS does not respect object ordering of keys
// we keep a list of the keys and their ordering
// in the snapshot event
NSEnumerator *children = [snapshot children];
FIRDataSnapshot *child;
while (child = [children nextObject]) {
[childKeys addObject:child.key];
}
}
dict[@"childKeys"] = childKeys;
[dict setValue:@(snapshot.hasChildren) forKey:@"hasChildren"];
[dict setValue:@(snapshot.exists) forKey:@"exists"];
[dict setValue:@(snapshot.childrenCount) forKey:@"childrenCount"];
[dict setValue:snapshot.priority forKey:@"priority"];
return dict;
}
- (NSDictionary *)getAndSendDatabaseError:(NSError *)error listenerId:(NSNumber *)listenerId {
NSDictionary *event = @{@"eventName": DATABASE_ERROR_EVENT, @"path": _path, @"refId": _refId, @"listenerId": listenerId, @"code": @([error code]), @"details": [error debugDescription], @"message": [error localizedDescription], @"description": [error description]};
@try {
[_emitter sendEventWithName:DATABASE_ERROR_EVENT body:event];
} @catch (NSException *err) {
NSLog(@"An error occurred in getAndSendDatabaseError: %@", [err debugDescription]);
NSLog(@"Tried to send: %@ with %@", DATABASE_ERROR_EVENT, event);
}
return event;
}
- (void)sendJSEvent:(NSString *)type title:(NSString *)title props:(NSDictionary *)props {
@try {
[_emitter sendEventWithName:type body:@{@"eventName": title, @"body": props}];
} @catch (NSException *err) {
NSLog(@"An error occurred in sendJSEvent: %@", [err debugDescription]);
NSLog(@"Tried to send: %@ with %@", title, props);
}
}
- (FIRDatabaseQuery *)buildQueryAtPathWithModifiers:(FIRDatabase *)database path:(NSString *)path modifiers:(NSArray *)modifiers {
FIRDatabaseQuery *query = [[database reference] child:path];
for (NSDictionary *modifier in modifiers) {
NSString *type = [modifier valueForKey:@"type"];
NSString *name = [modifier valueForKey:@"name"];
if ([type isEqualToString:@"orderBy"]) {
if ([name isEqualToString:@"orderByKey"]) {
query = [query queryOrderedByKey];
} else if ([name isEqualToString:@"orderByPriority"]) {
query = [query queryOrderedByPriority];
} else if ([name isEqualToString:@"orderByValue"]) {
query = [query queryOrderedByValue];
} else if ([name isEqualToString:@"orderByChild"]) {
NSString *key = [modifier valueForKey:@"key"];
query = [query queryOrderedByChild:key];
}
} else if ([type isEqualToString:@"limit"]) {
int limit = [[modifier valueForKey:@"limit"] integerValue];
if ([name isEqualToString:@"limitToLast"]) {
query = [query queryLimitedToLast:limit];
} else if ([name isEqualToString:@"limitToFirst"]) {
query = [query queryLimitedToFirst:limit];
}
} else if ([type isEqualToString:@"filter"]) {
NSString *valueType = [modifier valueForKey:@"valueType"];
NSString *key = [modifier valueForKey:@"key"];
id value = [self getIdValue:[modifier valueForKey:@"value"] type:valueType];
if ([name isEqualToString:@"equalTo"]) {
if (key != nil) {
query = [query queryEqualToValue:value childKey:key];
} else {
query = [query queryEqualToValue:value];
}
} else if ([name isEqualToString:@"endAt"]) {
if (key != nil) {
query = [query queryEndingAtValue:value childKey:key];
} else {
query = [query queryEndingAtValue:value];
}
} else if ([name isEqualToString:@"startAt"]) {
if (key != nil) {
query = [query queryStartingAtValue:value childKey:key];
} else {
query = [query queryStartingAtValue:value];
}
}
}
}
return query;
}
- (id)getIdValue:(NSString *)value type:(NSString *)type {
if ([type isEqualToString:@"number"]) {
return @(value.doubleValue);
} else if ([type isEqualToString:@"boolean"]) {
return @(value.boolValue);
} else {
return value;
}
}
- (BOOL)hasListeners {
return [[_listeners allKeys] count] > 0;
}
- (int)eventTypeFromName:(NSString *)name {
int eventType = FIRDataEventTypeValue;
if ([name isEqualToString:DATABASE_VALUE_EVENT]) {
eventType = FIRDataEventTypeValue;
} else if ([name isEqualToString:DATABASE_CHILD_ADDED_EVENT]) {
eventType = FIRDataEventTypeChildAdded;
} else if ([name isEqualToString:DATABASE_CHILD_MODIFIED_EVENT]) {
eventType = FIRDataEventTypeChildChanged;
} else if ([name isEqualToString:DATABASE_CHILD_REMOVED_EVENT]) {
eventType = FIRDataEventTypeChildRemoved;
} else if ([name isEqualToString:DATABASE_CHILD_MOVED_EVENT]) {
eventType = FIRDataEventTypeChildMoved;
}
return eventType;
}
#endif
@end

View File

@ -1,10 +1,10 @@
#ifndef RNFirebaseMessaging_h
#define RNFirebaseMessaging_h
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#if __has_include(<FirebaseMessaging/FirebaseMessaging.h>)
#import <FirebaseMessaging/FirebaseMessaging.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@import UserNotifications;
@ -21,12 +21,14 @@ typedef void (^RCTNotificationResponseCallback)();
+ (void)didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo;
+ (void)didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull RCTRemoteNotificationCallback)completionHandler;
+ (void)didReceiveLocalNotification:(nonnull UILocalNotification *)notification;
+ (void)didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull RCTNotificationResponseCallback)completionHandler;
+ (void)willPresentNotification:(nonnull UNNotification *)notification withCompletionHandler:(nonnull RCTWillPresentNotificationCallback)completionHandler;
#endif
@end
#else
@interface RNFirebaseMessaging : NSObject<RCTBridgeModule>
@interface RNFirebaseMessaging : NSObject
@end
#endif

View File

@ -145,6 +145,24 @@ RCT_EXPORT_MODULE()
[[NSNotificationCenter defaultCenter] postNotificationName:MESSAGING_NOTIFICATION_RECEIVED object:self userInfo:@{@"data": data}];
}
+ (void)willPresentNotification:(UNNotification *)notification withCompletionHandler:(nonnull RCTWillPresentNotificationCallback)completionHandler
{
NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: notification.request.content.userInfo];
[data setValue:@"will_present_notification" forKey:@"_notificationType"];
[[NSNotificationCenter defaultCenter] postNotificationName:MESSAGING_NOTIFICATION_RECEIVED object:self userInfo:@{@"data": data, @"completionHandler": completionHandler}];
}
+ (void)didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(nonnull RCTNotificationResponseCallback)completionHandler
{
NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: response.notification.request.content.userInfo];
[data setValue:@"notification_response" forKey:@"_notificationType"];
[data setValue:@YES forKey:@"opened_from_tray"];
if (response.actionIdentifier) {
[data setValue:response.actionIdentifier forKey:@"_actionIdentifier"];
}
[[NSNotificationCenter defaultCenter] postNotificationName:MESSAGING_NOTIFICATION_RECEIVED object:self userInfo:@{@"data": data, @"completionHandler": completionHandler}];
}
- (id)init {
self = [super init];
if (self != nil) {

View File

@ -1,6 +1,8 @@
#ifndef RNFirebasePerformance_h
#define RNFirebasePerformance_h
#import <Foundation/Foundation.h>
#if __has_include(<FirebasePerformance/FIRPerformance.h>)
#import <React/RCTBridgeModule.h>
@interface RNFirebasePerformance : NSObject <RCTBridgeModule> {
@ -11,4 +13,9 @@
@end
#else
@interface RNFirebasePerformance : NSObject
@end
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More