在Expo应用中请求通知权限时遇到错误。

huangapple go评论84阅读模式
英文:

Receiving error while reqeusting notification permission on expo app

问题

如果您使用的是设备,那么这是一个简单的代码,用于请求通知权限。以前可以正常工作,但突然间出现了以下错误:

"Error: Encountered an exception while calling native method: Exception occurred while executing exported method requestPermissionsAsync on module ExpoNotificationPermissionsModule: String resource ID #0xffffffff"

代码:
```ts
	if (isDevice) {
		const { status: existingStatus } = await Notifications.getPermissionsAsync();
		let finalStatus = existingStatus;
		if (existingStatus !== "granted") {
			const { status } = await Notifications.requestPermissionsAsync();
			finalStatus = status;
		}
		if (finalStatus !== "granted") {
			Alert.alert("Failed to obtain permission for push notifications!", "You need to allow push notifications for the app to function correctly.");
			return "";
		}
		token = (await Notifications.getExpoPushTokenAsync()).data;
	} else {
		alert("To generate the notification token, you need to be on a physical device!");
	}
英文:

I Have a simple code that asks for notifications permission that worked in the past, but suddently,It's giving me this error:

"Error: Encountered an exception while calling native method: Exception occurred while executing exported method requestPermissionsAsync on module ExpoNotificationPermissionsModule: String resource ID #0xffffffff"

Code:

	if (isDevice) {
		const { status: existingStatus } = await Notifications.getPermissionsAsync();
		let finalStatus = existingStatus;
		if (existingStatus !== "granted") {
			const { status } = await Notifications.requestPermissionsAsync();
			finalStatus = status;
		}
		if (finalStatus !== "granted") {
			Alert.alert("Falha ao obter permissão para notificações push!", "É necessário permitir o envio de notificações push para o aplicativo funcionar corretamente.");
			return "";
		}
		token = (await Notifications.getExpoPushTokenAsync()).data;
	} else {
		alert("Para gerar o token de notificação você precisa estar em um dispositivo físico!");
	}

答案1

得分: 16

在Android 13上,应用用户必须选择接收通知,通过操作系统自动触发的权限提示来实现。这个提示不会出现,直到至少创建一个通知通道。必须在调用getDevicePushTokenAsync或getExpoPushTokenAsync之前调用setNotificationChannelAsync来获取推送令牌。您可以在官方文档中了解有关Android 13的新通知权限行为的更多信息。

async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('无法获取推送通知的推送令牌!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('必须使用物理设备进行推送通知');
  }

  return token;
}

清除存储数据并卸载Expo Go应用。然后重新下载应用,应该会提示权限。

英文:

On Android 13, app users must opt-in to receive notifications via a permissions prompt automatically triggered by the operating system. This prompt will not appear until at least one notification channel is created. The setNotificationChannelAsync must be called before getDevicePushTokenAsync or getExpoPushTokenAsync to obtain a push token. You can read more about the new notification permission behavior for Android 13 in the official documentation.

async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  return token;
}

Clear storage data and Uninstall expo go app. Download it again and app should be prompting permission.

答案2

得分: 8

同样的情况在这里,直到最近都正常工作。甚至没有查看用于注册通知的代码部分。因为这与代码库无关,所以请在其他地方查找问题的来源。我的手机最近更新了新的操作系统版本,所以我已经卸载了 Expo 并清除了所有应用数据/存储。此外,我已经更新了 Expo-cli 并从未触摸过的代码库开始使用相同的设备。我被要求允许通知,这部分代码已经运行了。尽管安全存储现在不起作用 :-)。不管怎样,这是你的起点。

英文:

Same story here, it was working till recently. Didnt even look to part of code responsible for registering for notifications. Since it's not related to codebase look for issue source elswhere. My phone updated to new Os version recently, so i have uninstalled expo and clear all the app data/storage. Also i've updated expo-cli and started with untoutched codebase with the same device. I got prompted for permission for notifications and this part of code went trough. Although secure storage is not working now :-). Anyway that's a starting point for you.

答案3

得分: 1

卸载 Expo Go 并重新安装对我来说非常有效。我还使用 "npm install -g eas-cli" 更新了 expo-cli。希望对你有帮助。

英文:

Uninstalling Expo Go and reinstalling worked for me like a charm. I also updated the expo-cli using "npm install -g eas-cli". I hope this helps.

答案4

得分: 0

Irfan Muhammad的解决方案对我有用,

我还将registerForPushNotificationsAsync函数移到了App.js文件的顶部,然后卸载了Expo Go并重新安装了它。

不确定移动函数是否有所改变,但这就是我所做的。然后提示立即出现。

英文:

Irfan Muhammad's solution worked for me,

I also moved the registerForPushNotificationsAsync function to the top of my App.js file before I uninstalled expo go and reinstalled it.

Not sure if moving the function made a difference but it's what I did. The prompt then immediately came up.

答案5

得分: 0

For fixing this follow this: expo notification setup

  • Add this if not present
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }
  • Don't forget to add the projectId inside getExpoPushTokenAsync
  token = (
      await Notifications.getExpoPushTokenAsync({
        projectId: Constants.expoConfig.extra.eas.projectId,
      })
  • Put the whole code in a try-catch for detecting future issues
英文:

For fixing this follow this: expo notification setup

  • Add this if not present
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }
  • Don't forget to add the projectId inside getExpoPushTokenAsync
  token = (
      await Notifications.getExpoPushTokenAsync({
        projectId: Constants.expoConfig.extra.eas.projectId,
      })
  • Put the whole code in a try-catch for detecting future issues

答案6

得分: 0

@sreedeep 提到的提示很有用,但对于 FCM,您应该使用 getDevicePushTokenAsync 而不是 getExpoPushTokenAsync,如此处所述。

英文:

The tip related of @sreedeep is useful, but for FCM you should use getDevicePushTokenAsync instead of getExpoPushTokenAsync as described here

huangapple
  • 本文由 发表于 2023年2月23日 19:38:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定