Commit ee6f9fab authored by Libin Lu's avatar Libin Lu

init

parents
node_modules
node_modules
The MIT License (MIT)
Copyright (c) 2015 Howard Yang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# react-native-gcm-push-notification
Firebase notification for React Native Android and IOS
## Demo
https://github.com/oney/TestGcm
## Installation
- Run `npm install react-native-fcm --save`
- Run rnpm link
## Android Configuration
- In `android/build.gradle`
```gradle
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0'
classpath 'com.google.gms:google-services:3.0.0' // <- Add this line
```
- In `android/app/build.gradle`
```gradle
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services' // <- Add this line
...
```
- In `android/app/src/main/AndroidManifest.xml`, add these lines, be sure to change `com.xxx.yyy` to your package
```
<application
android:theme="@style/AppTheme">
...
<service android:name="com.evollu.react.fcm.MessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
...
```
### IOS Configuration
install pod 'Firebase/Messaging'
in AppDelegate.m add
```
#import "FCMModule.h"
```
```
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification {
[[NSNotificationCenter defaultCenter] postNotificationName: FCMNotificationReceived
object:self
userInfo:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
[[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived
object:self
userInfo:notification];
handler(UIBackgroundFetchResultNoData);
}
```
### FCM config file
In [firebase console](https://console.firebase.google.com/), you can get `google-services.json` file and place it in `android/app` directory and get `googleServices-info.plist` file and place it in `/ios` directory
### Usage
```javascript
var FCM = require('react-native-fcm');
componentWillMount() {
FCM.requestPermissions();
FCM.getFCMToken().then(token => {
//store fcm token in your server
});
this.fcmNotifLsnr = DeviceEventEmitter.addListener('FCMNotificationReceived', (notif) => {
//there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
});
this.fcmTokenLsnr = DeviceEventEmitter.addListener('FCMTokenRefreshed', (token) => {
//fcm token may not be available on first load, catch it here
});
}
componentWillUnmount() {
//prevent leak
this.fcmNotifLsnr.remove();
this.fcmTokenLsnr.remove();
}
}
```
## Q & A
### Why my android build is co
### Why I don't get data notification when app is killed?
If you send notification with payload only, you can only get the data message when app is in foreground or background. Killed app can't show notification
### Why I don't get data notification when I'm sending hybrid notification when app is in background?
I want to figure it out too. Looks like that is how GCM/FCM works. I'm sending 2 notification separately for now. Let me know if you find a better solution
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
minSdkVersion 16
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.facebook.react:react-native:0.17.+'
compile 'com.google.firebase:firebase-core:9.0.1'
compile 'com.google.firebase:firebase-messaging:9.0.1'
}
This diff is collapsed.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.oney.gcm">
</manifest>
package com.evollu.react.fcm;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.RemoteMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.json.*;
import android.preference.PreferenceManager;
import android.util.Log;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.content.res.Resources;
import android.app.PendingIntent;
import android.app.Notification;
import android.app.NotificationManager;
import android.media.RingtoneManager;
import android.net.Uri;
public class FCMModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
private final static String TAG = FCMModule.class.getCanonicalName();
public FCMModule(ReactApplicationContext reactContext, Intent intent) {
super(reactContext);
if (getReactApplicationContext().hasCurrentActivity()) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(reactContext);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("GcmMainActivity", getCurrentActivity().getClass().getSimpleName());
editor.apply();
}
getReactApplicationContext().addLifecycleEventListener(this);
registerNotificationHandler();
registerTokenRefreshHandler();
}
@Override
public String getName() {
return "FCMModule";
}
@ReactMethod
public void requestPermissions(){
}
@ReactMethod
public void getFCMToken(Promise promise) {
Log.d(TAG, "Firebase token: " + FirebaseInstanceId.getInstance().getToken());
promise.resolve(FirebaseInstanceId.getInstance().getToken());
}
private void sendEvent(String eventName, Object params) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
private void registerTokenRefreshHandler() {
IntentFilter intentFilter = new IntentFilter("com.evollu.react.fcm.FCMRefreshToken");
getReactApplicationContext().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
String token = intent.getStringExtra("token");
WritableMap params = Arguments.createMap();
params.putString("token", token);
sendEvent("FCMTokenRefreshed", params);
abortBroadcast();
}
}
}, intentFilter);
}
private void registerNotificationHandler() {
IntentFilter intentFilter = new IntentFilter("com.evollu.fcm.ReceiveNotification");
getReactApplicationContext().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getReactApplicationContext().hasActiveCatalystInstance()) {
WritableMap params = Arguments.createMap();
if(intent.getStringExtra("data") != null){
params.putString("data", intent.getStringExtra("data"));
}
if(intent.getStringExtra("notification") != null){
params.putString("notification", intent.getStringExtra("notification"));
}
sendEvent("FCMNotificationReceived", params);
abortBroadcast();
}
}
}, intentFilter);
}
// @Override
// public Map<String, Object> getConstants() {
// final Map<String, Object> constants = new HashMap<>();
// if (mIntent != null) {
// Bundle bundle = mIntent.getBundleExtra("bundle");
// String bundleString = convertJSON(bundle);
// Log.d(TAG, "bundleString: " + bundleString);
// constants.put("initialNotification", bundleString);
// }
// return constants;
// }
// private void sendEvent(String eventName, Object params) {
// getReactApplicationContext()
// .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
// .emit(eventName, params);
// }
// private void listenGcmRegistration() {
// IntentFilter intentFilter = new IntentFilter("RNGcmRegistrationServiceResult");
//
// getReactApplicationContext().registerReceiver(new BroadcastReceiver() {
// @Override
// public void onReceive(Context context, Intent intent) {
// Bundle bundle = intent.getExtras();
// boolean success = bundle.getBoolean("success");
// if (success) {
// String token = bundle.getString("token");
// WritableMap params = Arguments.createMap();
// params.putString("registrationToken", token);
// registrationToken = token;
//
// sendEvent("GCMRemoteNotificationRegistered", params);
// } else {
// String message = bundle.getString("message");
// WritableMap params = Arguments.createMap();
// params.putString("error", message);
//
// sendEvent("GCMRemoteNotificationRegistered", params);
//
// }
// }
// }, intentFilter);
// }
// private String convertJSON(Bundle bundle) {
// JSONObject json = new JSONObject();
// Set<String> keys = bundle.keySet();
// for (String key : keys) {
// try {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// json.put(key, JSONObject.wrap(bundle.get(key)));
// } else {
// json.put(key, bundle.get(key));
// }
// } catch(JSONException e) {
// return null;
// }
// }
// return json.toString();
// }
// private void listenGcmReceiveNotification() {
// IntentFilter intentFilter = new IntentFilter("com.oney.gcm.GCMReceiveNotification");
//
// getReactApplicationContext().registerReceiver(new BroadcastReceiver() {
// @Override
// public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "GCMReceiveNotification BroadcastReceiver");
//
// if (getReactApplicationContext().hasActiveCatalystInstance()) {
// Bundle bundle = intent.getBundleExtra("bundle");
//
// String bundleString = convertJSON(bundle);
//
// WritableMap params = Arguments.createMap();
// params.putString("dataJSON", bundleString);
// params.putBoolean("isInForeground", mIsInForeground);
//
// sendEvent("GCMRemoteNotificationReceived", params);
// abortBroadcast();
// } else {
// }
// }
// }, intentFilter);
// }
// @ReactMethod
// public void stopService() {
// if (mIntent != null) {
// new android.os.Handler().postDelayed(new Runnable() {
// public void run() {
// getReactApplicationContext().stopService(mIntent);
// }
// }, 1000);
// }
// }
// private Class getMainActivityClass() {
// try {
// String packageName = getReactApplicationContext().getPackageName();
//
// SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getReactApplicationContext());
// String activityString = preferences.getString("GcmMainActivity", null);
// if (activityString == null) {
// Log.d(TAG, "GcmMainActivity is null");
// return null;
// } else {
// return Class.forName(packageName + "." + activityString);
// }
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return null;
// }
// }
@Override
public void onHostResume() {
}
@Override
public void onHostPause() {
}
@Override
public void onHostDestroy() {
}
}
package com.evollu.react.fcm;
import android.content.Intent;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class FCMPackage implements ReactPackage {
public FCMPackage() {
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new FCMModule(reactContext, null));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList();
}
}
package com.evollu.react.fcm;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class InstanceIdService extends FirebaseInstanceIdService {
private static final String TAG = "InstanceIdService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. This call is initiated by the
* InstanceID provider.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// Broadcast refreshed token
Intent i = new Intent("com.evollu.react.fcm.FCMRefreshToken");
Bundle bundle = new Bundle();
bundle.putString("token", refreshedToken);
i.putExtras(bundle);
sendBroadcast(i);
}
}
package com.evollu.react.fcm;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;;import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import java.util.Set;
public class MessagingService extends FirebaseMessagingService {
private static final String TAG = "MessagingService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "Remote message received");
Intent i = new Intent("com.evollu.fcm.ReceiveNotification");
if(remoteMessage.getData() != null){
i.putExtra("data", convertJSON(remoteMessage.getData()));
}
if(remoteMessage.getNotification() != null){
i.putExtra("notification", buildNotificationJSON(remoteMessage.getNotification()));
}
sendOrderedBroadcast(i, null);
}
private String buildNotificationJSON(RemoteMessage.Notification notification){
JSONObject json = new JSONObject();
try{
json.put("title", notification.getTitle());
json.put("body", notification.getBody());
json.put("icon", notification.getIcon());
json.put("sound", notification.getSound());
json.put("color", notification.getColor());
} catch( JSONException e){
return null;
}
return json.toString();
}
private String convertJSON(Map data) {
JSONObject json = new JSONObject();
Set<String> keys = data.keySet();
for (String key : keys) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
json.put(key, JSONObject.wrap(data.get(key)));
} else {
json.put(key, data.get(key));
}
} catch(JSONException e) {
return null;
}
}
return json.toString();
}
}
'use strict';
var React = require('react-native');
var {
NativeModules
} = React;
var FCMModule = NativeModules.FCMModule;
class FCM {
static getFCMToken() {
return FCMModule.getFCMToken();
}
static requestPermissions() {
return FCMModule.requestPermissions();
}
constructor(data) {
this.data = data;
}
}
module.exports = FCM;
\ No newline at end of file
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
3AD1DC2B1CFA802F008C092E /* FCMModule.m in Sources */ = {isa = PBXBuildFile; fileRef = 3AD1DC2A1CFA802F008C092E /* FCMModule.m */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
58B511D91A9E6C8500147676 /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "include/$(PRODUCT_NAME)";
dstSubfolderSpec = 16;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
134814201AA4EA6300B7C361 /* libRNGCM.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRNGCM.a; sourceTree = BUILT_PRODUCTS_DIR; };
3AD1DC291CFA802F008C092E /* FCMModule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FCMModule.h; sourceTree = "<group>"; };
3AD1DC2A1CFA802F008C092E /* FCMModule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FCMModule.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
58B511D81A9E6C8500147676 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
134814211AA4EA7D00B7C361 /* Products */ = {
isa = PBXGroup;
children = (
134814201AA4EA6300B7C361 /* libRNGCM.a */,
);
name = Products;
sourceTree = "<group>";
};
58B511D21A9E6C8500147676 = {
isa = PBXGroup;
children = (
3AD1DC291CFA802F008C092E /* FCMModule.h */,
3AD1DC2A1CFA802F008C092E /* FCMModule.m */,
134814211AA4EA7D00B7C361 /* Products */,
);
indentWidth = 2;
sourceTree = "<group>";
tabWidth = 2;
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
58B511DA1A9E6C8500147676 /* RNGCM */ = {
isa = PBXNativeTarget;
buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNGCM" */;
buildPhases = (
58B511D71A9E6C8500147676 /* Sources */,
58B511D81A9E6C8500147676 /* Frameworks */,
58B511D91A9E6C8500147676 /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = RNGCM;
productName = RCTDataManager;
productReference = 134814201AA4EA6300B7C361 /* libRNGCM.a */;
productType = "com.apple.product-type.library.static";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
58B511D31A9E6C8500147676 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0610;
ORGANIZATIONNAME = Facebook;
TargetAttributes = {
58B511DA1A9E6C8500147676 = {
CreatedOnToolsVersion = 6.1.1;
};
};
};
buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "FCM" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = 58B511D21A9E6C8500147676;
productRefGroup = 58B511D21A9E6C8500147676;
projectDirPath = "";
projectRoot = "";
targets = (
58B511DA1A9E6C8500147676 /* RNGCM */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
58B511D71A9E6C8500147676 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
3AD1DC2B1CFA802F008C092E /* FCMModule.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
58B511ED1A9E6C8500147676 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1";
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
GCC_WARN_SHADOW = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
WARNING_CFLAGS = (
"-Wextra",
"-Wall",
);
};
name = Debug;
};
58B511EE1A9E6C8500147676 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_PREPROCESSOR_DEFINITIONS = "";
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
GCC_WARN_SHADOW = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
WARNING_CFLAGS = (
"-Wextra",
"-Wall",
);
};
name = Release;
};
58B511F01A9E6C8500147676 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_STATIC_ANALYZER_MODE = deep;
GCC_PREPROCESSOR_DEFINITIONS = "$(inherited)";
HEADER_SEARCH_PATHS = (
"$(SRCROOT)/../../react-native/React/**",
"$(SRCROOT)/../../../ios/Pods/**",
);
LIBRARY_SEARCH_PATHS = "$(inherited)";
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = RNGCM;
RUN_CLANG_STATIC_ANALYZER = YES;
SKIP_INSTALL = YES;
};
name = Debug;
};
58B511F11A9E6C8500147676 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_STATIC_ANALYZER_MODE = deep;
HEADER_SEARCH_PATHS = (
"$(SRCROOT)/../../react-native/React/**",
"$(SRCROOT)/../../../ios/Pods/**",
);
LIBRARY_SEARCH_PATHS = "$(inherited)";
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = RNGCM;
SKIP_INSTALL = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "FCM" */ = {
isa = XCConfigurationList;
buildConfigurations = (
58B511ED1A9E6C8500147676 /* Debug */,
58B511EE1A9E6C8500147676 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNGCM" */ = {
isa = XCConfigurationList;
buildConfigurations = (
58B511F01A9E6C8500147676 /* Debug */,
58B511F11A9E6C8500147676 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 58B511D31A9E6C8500147676 /* Project object */;
}
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:/Users/libinlu/Code/react-native-gcm/ios/RNGCM.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "58B511DA1A9E6C8500147676"
BuildableName = "libRNGCM.a"
BlueprintName = "RNGCM"
ReferencedContainer = "container:FCM.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<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">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "58B511DA1A9E6C8500147676"
BuildableName = "libRNGCM.a"
BlueprintName = "RNGCM"
ReferencedContainer = "container:FCM.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "58B511DA1A9E6C8500147676"
BuildableName = "libRNGCM.a"
BlueprintName = "RNGCM"
ReferencedContainer = "container:FCM.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?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>SchemeUserState</key>
<dict>
<key>RNGCM.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>20</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>58B511DA1A9E6C8500147676</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "58B511DA1A9E6C8500147676"
BuildableName = "libRNGCM.a"
BlueprintName = "RNGCM"
ReferencedContainer = "container:RNGCM.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<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">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "58B511DA1A9E6C8500147676"
BuildableName = "libRNGCM.a"
BlueprintName = "RNGCM"
ReferencedContainer = "container:RNGCM.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "58B511DA1A9E6C8500147676"
BuildableName = "libRNGCM.a"
BlueprintName = "RNGCM"
ReferencedContainer = "container:RNGCM.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?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>SchemeUserState</key>
<dict>
<key>RCTPushNotification.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>9</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>58B511DA1A9E6C8500147676</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>
#import <UIKit/UIKit.h>
#import <Firebase.h>
#import "RCTBridgeModule.h"
extern NSString *const FCMNotificationReceived;
@interface FCMModule : NSObject <RCTBridgeModule>
@property (nonatomic, assign) bool connectedToFCM;
@end
#import "FCMModule.h"
#import "RCTBridge.h"
#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTUtils.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
#define UIUserNotificationTypeAlert UIRemoteNotificationTypeAlert
#define UIUserNotificationTypeBadge UIRemoteNotificationTypeBadge
#define UIUserNotificationTypeSound UIRemoteNotificationTypeSound
#define UIUserNotificationTypeNone UIRemoteNotificationTypeNone
#define UIUserNotificationType UIRemoteNotificationType
#endif
NSString *const FCMNotificationReceived = @"FCMNotificationReceived";
@implementation FCMModule
NSString* registrationToken;
RCT_EXPORT_MODULE()
@synthesize bridge = _bridge;
- (NSDictionary<NSString *, id> *)constantsToExport
{
NSDictionary<NSString *, id> *initialNotification =
[_bridge.launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] copy];
return @{@"initialNotification": RCTNullIfNil(initialNotification)};
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setBridge:(RCTBridge *)bridge
{
_bridge = bridge;
[FIRApp configure];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleRemoteNotificationReceived:)
name:FCMNotificationReceived
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(disconnectFCM)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(connectToFCM)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(onTokenRefresh)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
}
- (void)connectToFCM
{
[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Unable to connect to FCM. %@", error);
} else {
NSLog(@"Connected to FCM.");
}
}];
}
- (void)disconnectFCM
{
[[FIRMessaging messaging] disconnect];
NSLog(@"Disconnected from FCM");
}
RCT_REMAP_METHOD(getFCMToken,
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
resolve([[FIRInstanceID instanceID] token]);
}
- (void) onTokenRefresh
{
NSDictionary *info = @{@"token":[[FIRInstanceID instanceID] token]};
[_bridge.eventDispatcher sendDeviceEventWithName:@"FCMTokenRefreshed"
body:info];
}
RCT_EXPORT_METHOD(requestPermissions)
{
if (RCTRunningInAppExtension()) {
return;
}
//UIApplication *app = RCTSharedApplication();
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
// iOS 7.1 or earlier
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:allNotificationTypes];
} else {
// iOS 8 or later
// [END_EXCLUDE]
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}
- (void)handleRemoteNotificationReceived:(NSNotification *)notification
{
[_bridge.eventDispatcher sendDeviceEventWithName:FCMNotificationReceived
body:notification.userInfo];
}
//- (void)handleRemoteNotificationsRegistered:(NSNotification *)notification
//{
// if([notification.userInfo objectForKey:@"deviceToken"] != nil){
// NSData* deviceToken = [notification.userInfo objectForKey:@"deviceToken"];
// __weak typeof(self) weakSelf = self;;
//
// NSDictionary *registrationOptions = @{kGGLInstanceIDRegisterAPNSOption:deviceToken,
// kGGLInstanceIDAPNSServerTypeSandboxOption:@YES};
//
// NSString* gcmSenderID = [[[GGLContext sharedInstance] configuration] gcmSenderID];
//
// [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:gcmSenderID scope:kGGLInstanceIDScopeGCM options:registrationOptions
// handler:^(NSString *token, NSError *error){
// if (token != nil) {
// NSLog(@"Registration Token: %@", token);
//
// weakSelf.connectedToGCM = YES;
// registrationToken = token;
//
// NSDictionary *userInfo = @{@"registrationToken":token};
// [_bridge.eventDispatcher sendDeviceEventWithName:GCMRemoteNotificationRegistered
// body:userInfo];
// } else {
// NSLog(@"Registration to GCM failed with error: %@", error.localizedDescription);
// NSDictionary *userInfo = @{@"error":error.localizedDescription};
// [_bridge.eventDispatcher sendDeviceEventWithName:GCMRemoteNotificationRegistered
// body:userInfo];
// }
// }];
// } else {
// [_bridge.eventDispatcher sendDeviceEventWithName:GCMRemoteNotificationRegistered
// body:notification.userInfo];
// }
//
//}
//-(void)onTokenRefresh {
// [self requestPermissions];
//}
@end
{
"name": "react-native-gcm-push-notification",
"version": "1.0.3",
"description": "React Native component for Google Cloud Messaging for IOS and Android",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/evollu/react-native-gcm-push-notification.git"
},
"keywords": [
"React-Native",
"ios",
"android",
"gcm"
],
"author": "Libin Lu",
"license": "MIT",
"bugs": {
"url": "https://github.com/evollu/react-native-gcm-push-notification/issues"
},
"homepage": "https://github.com/evollu/react-native-gcm-push-notification#readme"
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment