Expo Notification Error in ios [Error: Another async call to this method is in progress. Await the first Promise.] - ios

Please provide the following:
SDK Version: "^42.0.0",
Platforms(Android/iOS/web/all): iOS
Add the appropriate "Tag" based on what Expo library you have a question on.
Hello,
[expo-notifications] Error encountered while updating server registration with latest device push token., [Error: Another async call to this method is in progress. Await the first Promise.]
This error often occurs in expo app. And always occurs in build ios app.
Using the following code:
async function registerForPushNotificationsAsync() {
let token
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync()
let finalStatus = existingStatus
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync({
ios: {
allowAlert: true,
allowBadge: true,
allowSound: true,
allowAnnouncements: true,
},
})
finalStatus = status
}
if (finalStatus !== 'granted') {
console.log('noti cancel')
return
}
// token = (await Notifications.getExpoPushTokenAsync()).data
try {
await Notifications.getExpoPushTokenAsync().then((res) => {
console.log('getExpoPUshTokenAsync >> ', res)
token = res.data
})
} catch (err) {
console.log('getExpoPushTokenAsync error >> ', err)
}
} else {
Alert.alert(
'Must use physical device for Push Notifications'
)
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
})
}
return token
}
I have received a new credential, but I am still getting the error.

Related

IOS Notification Permission alert does not show

SDK Version: 39.0.0
Platforms(Android/iOS/web/all): All
I am not getting accept or decline notifications permissions alert when loading my app in production.
I have tried clearing certificates and keys and allowing expo to add everything from a clean slate, but still no luck. I am starting to think maybe it’s my code which is the reason why the alert doesn’t get fired.
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import { Permissions } from "expo-permissions";
import { Notifications as Notifications2 } from "expo";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false
})
});
export default class LoginScreen extends React.Component {
state = {
email: "",
password: "",
notification: {},
errorMessage: null
};
async componentDidMount() {
this.registerForPushNotificationsAsync();
//Notifications.addNotificationReceivedListener(this._handleNotification);
Notifications2.addListener(data => {
this.setState({ notification: data });
});
Notifications.addNotificationResponseReceivedListener(
this._handleNotificationResponse
);
}
_handleNotification = notification => {
this.setState({ notification: notification });
};
_handleNotificationResponse = response => {
console.log(response);
};
handleLogin = async () => {
try {
const { email, password } = this.state;
const expoPushToken = await Notifications.getExpoPushTokenAsync();
console.log(expoPushToken);
const userinfo = await firebase
.auth()
.signInWithEmailAndPassword(email, password);
console.log("user ID ", userinfo.user.uid);
await firebase
.firestore()
.collection("users")
.doc(userinfo.user.uid.toString())
.update({
expo_token: expoPushToken["data"]
})
.then(function() {
console.log("token successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
} catch (error) {
console.log("=======Error in login", error);
this.setState({ errorMessage: error.message });
}
};
registerForPushNotificationsAsync = async () => {
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(
Permissions.NOTIFICATIONS
);
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
const token = await Notifications.getExpoPushTokenAsync();
console.log(token);
//this.setState({ expoPushToken: token });
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C"
});
}
};
import { Permissions } from "expo-permissions";
should of been
import * as Permissions from 'expo-permissions';
Sometimes we all make simple mistakes.

TypeError: Undefined is not an object (evaluating '_pushNotifications.pushNotifications.configure') React Native

I am new to React Native and am trying to create push notifications on iOS with push-notification-ios and react-native-push-notification. I am following a number of different tutorials on this as I am still learning how it works.
When I run my app I get the following error.
Here is my code
const configure = async () => {
console.log('push notification configured');
PushNotificationIOS.addEventListener('registrationError', (e) => {
PushNotifcation.configure({
onRegister: function(token) {
//process token
alert('Token!' + JSON.stringify(token));
console.log('[CATCHED] onRegister:', token);
db.setToken(token).catch(
console.log('[ERROR] device push token has not been saved on the database'),
);
},
onNotification: async function(notification) {
console.log('[CATCHED] onNotification:' + JSON.stringify(notification));
let notifType = '';
if (Platform.OS === 'ios') {
notifType = getNotificationType(
JSON.parse(notification.data.data).type,
);
} else {
notifType = getNotificationType(
notification.type,
);
}
//process the notification
//required on iOS only
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
},
senderID: '-----',
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
});
});
}
export {
configure,
};
Line 5: you typed PushNotifcation instead PushNotification.
The fixed code is here:
const configure = async () => {
console.log('push notification configured');
PushNotificationIOS.addEventListener('registrationError', (e) => {
PushNotification.configure({
onRegister: function(token) {
//process token
alert('Token!' + JSON.stringify(token));
console.log('[CATCHED] onRegister:', token);
db.setToken(token).catch(
console.log('[ERROR] device push token has not been saved on the database'),
);
},
onNotification: async function(notification) {
console.log('[CATCHED] onNotification:' + JSON.stringify(notification));
let notifType = '';
if (Platform.OS === 'ios') {
notifType = getNotificationType(
JSON.parse(notification.data.data).type,
);
} else {
notifType = getNotificationType(
notification.type,
);
}
//process the notification
//required on iOS only
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
},
senderID: '-----',
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
});
});
}
export {
configure,
};
You have re-build your app try:
yarn android
OR
cd android && ./gradlew clean && cd .. && react-native run-android
Good Luck :)
Your import must be the wrong path
Try this:
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '#react-native-community/push-notificatio-ios';

don't display notification in ios device when use react-native-fcm

i'm using from react-native-fcm for recieve pushNotification and do all config in this document(https://github.com/evollu/react-native-fcm)
in ios device only recieve notification and call notificationListener that checked by console.log but dont display notification message and alert even test FCM.presentLocalNotification for show local notification still dont show notification
async componentDidMount() {
if (Platform.OS === 'ios') {
try {
const result = await FCM.requestPermissions({ badge: false, sound: true, alert: true });
} catch (e) {
console.error(e);
}
FCM.getFCMToken().then(token => {
if (token !== undefined) {
// this.props.onChangeToken(token);
} else {
console.log('TOKEN (getFCMToken)', 'null');
}
});
// FCM.getAPNSToken().then(token => {
// this.props.onAPNToken(token);
// });
FCM.getInitialNotification().then(notif => {
console.log('INITIAL NOTIFICATION', notif);
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
console.log(" >> notificationListener: ", notif)
if (notif.local_notification) return;
FCM.presentLocalNotification({
body: 'tdtydt',
priority: "high",
title: 'notif.fcm.title',
sound: "default",
show_in_foreground: true,
local_notification: true,
icon: "ic_launcher",
status: "400"
});
});
this.refreshTokenListener = FCM.on(FCMEvent.RefreshToken, token => {
console.log('TOKEN (refreshUnsubscribe)', token);
this.props.onChangeToken(token);
});
FCM.enableDirectChannel();
this.channelConnectionListener = FCM.on(FCMEvent.DirectChannelConnectionChanged, (data) => {
console.log(`direct channel connected${data}`);
});
setTimeout(() => {
FCM.isDirectChannelEstablished().then(d => console.log('isDirectChannelEstablished', d));
}, 500);
}

Cloud Function for Firebase sendToDevice not showing as notification on ios

Upon sending a successful notification via Cloud Functions for Firebase, the notification is not shown as a push notification on ios device. I have found a couple of similar issues, but none present a clear solution.
cloud function:
exports.sendInitialNotification = functions.database.ref('branches/{branchId}/notifications/{notifId}').onWrite(event => {
const data = event.data.val()
if (data.finished) return
const tokens = []
const notifId = event.params.notifId
const getPayload = admin.database().ref(`notifications/${notifId}`).once('value').then(snapshot => {
const notif = snapshot.val()
const payload = {
notification: {
title: notif.title,
body: notif.message,
},
data: {
'title': notif.title,
'message': notif.message,
'id': String(notif.id),
}
}
if (notif.actions) {
payload.data['actions'] = JSON.stringify(notif.actions)
}
console.log('payload:', payload)
return payload
}, (error) => {
console.log('error at sendInitialNotification getPayload():', error)
})
const getTokens = admin.database().ref(`notifications/${notifId}/users`).once('value').then(snapshot => {
const users = snapshot.forEach((data) => {
let promise = admin.database().ref(`users/${data.key}/profile/deviceToken`).once('value').then(snap => {
if (tokens.indexOf(snap.val()) !== -1 || !snap.val()) return
return snap.val()
}, (error) => {
console.log('error retrieving tokens:', error)
})
tokens.push(promise)
})
return Promise.all(tokens)
}, (error) => {
console.log('error at sendInitialNotification getTokens()', error)
}).then((values) => {
console.log('tokens:', values)
return values
})
return Promise.all([getTokens, getPayload]).then(results => {
const tokens = results[0]
const payload = results[1]
if (payload.actions) {
payload.actions = JSON.stringify(payload.actions)
}
const options = {
priority: "high",
}
admin.messaging().sendToDevice(tokens, payload, options)
.then(response => {
data.finished = true
admin.database().ref(`notifications/${notifId}`).update({success: true, successCount: response.successCount})
console.log('successfully sent message', response)
}).catch(error => {
data.finished = true
admin.database().ref(`notifications/${notifId}`).update({success: false, error: error})
console.log('error sending message:', error)
})
})
})
...and the logs in firebase console:
successfully sent message { results: [ { error: [Object] } ],
canonicalRegistrationTokenCount: 0, failureCount: 1, successCount:
0, multicastId: 7961281827678412000 }
tokens: [
'eS_Gv0FrMC4:APA91bEBk7P1lz...' ]
payload: { notification: { title: 'test07', body: 'test07' }, data:
{ title: 'test07', message: 'test07', id: '1502383526361' } }
...but alas no notification shown on iphone. Im sure I am missing something along the OOO (order of operations) here, but not sure where the snag is. If anyone can point out my flaw please feel free to publicly chastise.
As always thank you in advance and any and all direction is appreciated!
The issue I was seeing was due to the reverse domain id in xcode not matching what was in firebase.
Typo

React Native IOS App crashes when no network conection

On the simulator it does not crash and Alerts the error, but in production it is crashes as soon as fetch request suppose to be made and it is impossible to reopen the app until network connection is back (I turn on/off airplane mode for the testing)
here are the snippets of my code
componentWillMount: function(){
NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange)
NetInfo.isConnected.fetch().done((data) => {
this.setState({
isConnected: data
})
console.log('this.state.isConnected: ', this.state.isConnected);
})
},
handleConnectivityChange: function(){
var connected = this.state.isConnected ? false : true
this.setState({isConnected: connected})
console.log('this.state.isConnected11: ', this.state.isConnected);
},
....
goToList: function(replace, listview){
console.log('this.state.isConnected: ', this.props.isConnected);
if (!this.props.isConnected){
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
return
}
....
fetch(url)
.then((response) => response.json())
.then((responseData) => {
....
.catch((error) => {
StatusBarIOS.setNetworkActivityIndicatorVisible(false)
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
})
.done()
I spent a lot of time trying to find a way to catch exceptions when using fetch() but I was unable to get it working (e.g. using .catch() or a try/catch blog didn't work). What did work was to use XMLHttpRequest with a try/catch blog instead of fetch(). Here's an example I based off of: https://facebook.github.io/react-native/docs/network.html#using-other-networking-libraries
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
var responseJson = JSON.parse(request.responseText);
// *use responseJson here*
} else {
console.warn('error');
}
};
try {
request.open('GET', 'https://www.example.org/api/something');
request.send();
} catch (error) {
console.error(error);
}

Resources