React Native Notification IOS - APN Configuration - ios

I have a problem with the configuration of push notification in IOS. I followed all the steps of the tutorial in the Invertase documentation (https://invertase.io/oss/react-native-firebase/v6/messaging/ios-configure-apns), but it didn't work. I read this article, and followed the steps up to the part of generating a development certificate (https://www.codementor.io/#uokesita/react-native-push-notifications-with-firebase-2019-10on0z19t6#generate-a-development-certificate). My JS code is as follows:
export default class App extends React.Component {
async componentDidMount() {
await messaging().registerForRemoteNotifications()
await messaging().requestPermission().then(async granted =>{
if (granted) {
console.log('User granted messaging permissions!');
if(Platform.OS === "ios"){
console.log("Token: " + await messaging().getToken())
}
} else {
console.log('User declined messaging permissions :(');
}
});
}
render() {
return (<AppContainer />)
}
}
Would anyone know to tell me why the notification does not want to appear? And when I request the Token as shown in the code below, the following error also appears:
[messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)

Related

Firebase Auth throwing "auth/internal-error" when trying to use PhoneAuthProvider method in Ionic React IOS mobile application

I am currently having some issues trying to integrate Google Firebase authentication into a React Ionic mobile application. So far I have been able to set up the app to run correctly on both web and android but am running into repeated issues with IOS. The code runs correctly for Firebase auth login on android does not seem to be running on IOS.
The initial call to "signInWithEmailAndPassword" seems to work fine and returns "auth/multi-factor-auth-required" but any time I try to make a call to "verifyPhoneNumber" on ios I will receive the response of "Firebase: An internal AuthError has occurred. (auth/internal-error)", there are no further details provided in any part of the error returned.
//Firebase setup in seperate file with code like these 2 lines
app.initializeApp(config);
const firebaseAuth = app.auth();
//
firebaseAuth
.signInWithEmailAndPassword(email, password)
.then(function (user) {
//other code
})
.catch(function (error) {
if (error.code === "auth/multi-factor-auth-required") {
let resolver = error.resolver;
setTimeout(() => {
phoneAuth(appVerifier, resolver);
}, 2000);
} else {
//other code
}
});
//following code is part of the method phoneAuth() above
var phoneInfoOptions = {
var phoneInfoOptions = {
multiFactorHint: resolver.hints[0],
session: resolver.session,
};
var phoneAuthProvider = new firebase.PhoneAuthProvider();
phoneAuthProvider
.verifyPhoneNumber(phoneInfoOptions, appVerifier)
.then(function (verificationId) {
console.log("verify Id recieved");
})
.catch((error) => {
console.log(error);
});
Things I have checked/tried so far are:
followed all steps in firebase docs
Setup ios app in firebase console and followed the steps listed
Has anyone run into issues like this previously and has any advice on what I could check next?
Thanks

React native app through Expo, getting firestore permission error:

This is my first post here so please let me know if I'm not posting this correctly.
I keep getting the following error in the debug logs of my react native Expo app on the iOS simulator when I have an authenticated user trying to retrieve a firestore document:
FirebaseError: [code=permission-denied]: Missing or insufficient permissions.
Here is firebase.js config file:
import "firebase/firestore";
import "firebase/storage";
import * as firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
apiKey: ... //removed for this post, but it is correct and validated
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();
export { auth };
export default db;
Here is my App.js:
import React, { useEffect, useState } from 'react';
import db, { auth } from './firebase';
const getUserData = async(uid) => {
try {
const doc = await db.collection('users').doc(uid).collection('info').doc(uid).get();
if (doc.exists) {
console.log(doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No user info was found for the authenticated user");
}
} catch(err) {
console.log(err);
}
};
useEffect(() => {
auth.onAuthStateChanged((authUser) => {
if (authUser) {
//user is logged in
getUserData(authUser.uid); //retrieve the user's profile data
} else {
//user is logged out
auth.signOut();
}
});
}, []);
My security rules shouldn't be the problem because it works for my web react app with the same logic and user, and the get request is only sent when there is a uid because the user is authenticated. I've printed out the uid after onAuthStateChanged and it is the correct uid.
//Security Rules in Firestore
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function signedInAndSameUser(uid) {
return request.auth != null && request.auth.uid == uid;
}
match /users/{uid} {
allow read: if request.auth != null;
match /private/{privateId} {
allow read: if signedInAndSameUser(privateId);
}
}
I've seen similar posts that recommended to downgrade to firebase#4.6.2 but I also ran into issues and couldn't get it to work. I'm wondering if firebase still hasn't fixed this issue even after version 8 (In react native app (through Expo) using firestore permissions - request.auth is always null)
This is my current firebase and expo version in my package.json:
//package.json
"expo": "~41.0.1",
"firebase": "8.2.3",
Thank you so much if you can help, I've been stuck on this issue for many hours and can't seem to understand why this works in my react.js web app, but the same logic, user, and security rules won't work in my react native Expo iOS app.

Ionic 5 Capacitor - Register push notification token after change in iOS settings

My code is set up as follows:
export class HomePage implements OnInit {
ngOnInit() {
console.log('Initializing HomePage');
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
PushNotifications.requestPermission().then( result => {
if (result.granted) {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
// On success, we should be able to receive notifications
PushNotifications.addListener('registration',
(token: PushNotificationToken) => {
alert('Push registration success, token: ' + token.value);
}
);
// Some issue with our setup and push will not work
PushNotifications.addListener('registrationError',
(error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
}
);
// Show us the notification payload if the app is open on our device
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotification) => {
alert('Push received: ' + JSON.stringify(notification));
}
);
// Method called when tapping on a notification
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
alert('Push action performed: ' + JSON.stringify(notification));
}
);
}
If the user denies permission on app first launch and then goes into the settings app and enables push notifications and then comes back to the app (without restarting the app) how do I access the registered token in this case? Do I need to register the token each time the app comes into the foreground as well as on app start? What is the recommended approach for an Ionic Capacitor app? Thanks!
I use platform.resume to test scenarios like this. You'll need capacitor3 for this as this was broken in capacitor2.

React Native Ios Push Notification Not Working

I use '#react-native-firebase/messaging' module to send notifications. On Android everything works fine, Following is the error log I get when I try const fcmToken = await firebase.messaging().getToken(); on ios device.
NativeFirebaseError: [messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
I have already implemented "react-native-permissions" to grant notification permission.
My AppDelegate.m contains :
if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
Should I add anything else to it?
Any help or suggestion will be very helpful.
Thanks in advance
You need to check and ask messaging permission before get the fcm token in iOS
/**
* Check is notification showing permission enabled if not ask the permission.
*/
async checkFcmPermission() {
firebase
.messaging()
.hasPermission()
.then(enabled => {
if (enabled) {
// User has permissions
this.getFcmToken(); // const fcmToken = await firebase.messaging().getToken();
} else {
// User doesn't have permission
firebase
.messaging()
.requestPermission()
.then(() => {
// User has authorized
this.getFcmToken(); // const fcmToken = await firebase.messaging().getToken();
})
.catch(error => {
// User has rejected permissions
console.log(
'PERMISSION REQUEST :: notification permission rejected',
);
});
}
});
}
There are a lot of solutions to this issue. I post my answer since some StackOverflow users requested.
Here is my code
const sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
};
async function requestPermissionForNotification() {
try {
const permission = await requestNotifications(["alert", "badge", "sound"]);
if (permission.status === "granted") {
setupNotification();
}
} catch (e) {
console.log(e)
}
};
async function setupNotification() {
try {
await sleep(5000)
// TODO no need token for now, Will be used for future releases
const enabled = await firebase.messaging().hasPermission();
await requestNotifications(['alert', 'badge', 'sound']);
await firebase.messaging().registerForRemoteNotifications();
const token = await firebase.messaging().getToken();
firebase.messaging().onMessage(async (remoteMessage) => {
});
} catch (e) {
console.log(e)
}
}
And Also I have added following to Info.plist
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
To sum up, I use react permissions to grant permission and the sleep method is to wait for firebase to be ready. Finally uninstalled app couple time to get a result.
When It started working, I couldn't dare to touch the code since I spent days on this.

react-native error RCTJSONStringify() encountered the following error: Invalid type in JSON write (NSURL)

I am trying to use react-native-fbsdk in my react-native app. It was working fine untill yesterday. But, today it gives a weird error stating RCTJSONStringify() encountered the following error: Invalid type in JSON write (NSURL).
RN v0.42.0
Here is my code:
_fbAuth(error, result) {
if (error) {
console.log("error");
alert("login has error: " + result.error);
} else if (result.isCancelled) {
console.log("login cancelled");
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then((data) => {
console.log("login success");
console.log(data.accessToken.toString());
let accessToken = data.accessToken;
alert(data.accessToken.toString());
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start();
});
}
}
render() {
console.log("in new render");
return (
<View style={styles.container}>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={this._fbAuth}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
The error information printed in debugger:
I get the above error while calling the graphAPI in the function responseInfoCallback. Any ideas what is happening ?
Update 1:
This error happens only when remote debugger is turned on!! Else it is not happening. But without remote debugger, I cannot proceed with developing the app. Are there any other methods to see log statements of react-native app other than remote debugger ?
Update 2:
The RCTJSONStringify() error happens only behind proxy. And also https fetch calls does not work under proxy. I tested in an open network, it works fine. I guess, it is to add some proxy information to RN app. I think it is related to APP transport security
If you turn the debugger off, you can see the proper error in the XCode console. Access it from Xcode menu View/Debug Area/Activate console, if it's not enabled automatically.

Resources