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.
Related
I am using 'react-native-geolocation-service' library for enabling the location for the app, if location is disabled. So if location is disabled then permission alert is working fine in android but In IOS it is appear for few second like 2 or 3 second, after that it will close. Below is the sample of method.
static hasLocationPermissionIOS = async () => {
const status = await Geolocation.requestAuthorization('always');
if (status === 'granted') {
return 'GRANTED';
}
if (status === 'denied') {
return 'DENIED';
}
if (status === 'disabled') {
return 'DISABLED';
}
};
static hasLocationPermission = async () => {
if (Platform.OS === 'ios') {
Geolocation.requestAuthorization('whenInUse');
const hasPermission = await this.hasLocationPermissionIOS();
return hasPermission;
}
if (Platform.OS === 'android') {
const hasPermission = await this.hasLocationPermissionAndroid();
return hasPermission;
}
return false;
};
static hasLocationPermission = async () => {
if (Platform.OS === 'ios') {
Geolocation.requestAuthorization('whenInUse');
const hasPermission = await this.hasLocationPermissionIOS();
return hasPermission;
}
if (Platform.OS === 'android') {
const hasPermission = await this.hasLocationPermissionAndroid();
return hasPermission;
}
return false;
};
static getLocation = async () => {
const hasLocationPermission = await this.hasLocationPermission();
if (!hasLocationPermission) {
return;
}
return new Promise((resolve, reject = (error) => {}) => {
Geolocation.getCurrentPosition((position)=> {
resolve(position);
}, (error)=>{
resolve(error);
}, {
accuracy: {
android: 'high',
ios: 'best',
},
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000,
distanceFilter: 0,
forceRequestLocation: true,
showLocationDialog: true,
});
});
};
I referred the link but not able to find solution,
https://github.com/douglasjunior/react-native-get-location/issues/18
Thanks in advance!!!
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.
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';
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);
}
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