How to request Push Notification Permission for iOS with react-native-permissions?

779 views Asked by At

I'm using react-native-permissions library to request permissions in our react-native app.

Currently I'm implementing push notification. For Android I can request Push Notification Permission with native modal using request(PERMISSIONS.ANDROID.POST_NOTIFICATIONS) . But for iOS I don't see a way to request push permission.

But

await checkNotifications()
  .then(({ status, settings }) => {
    console.log('CHECK STATUS: ', status);
    console.log('CHECK SETTINGS: ', settings);
  })
  .catch((err) => console.log('CHECK ERROR: ', err));

works though it doesn't open the modal. How can I request the push permission in iOS ?

2

There are 2 answers

0
Thidasa Pankaja On

Found it. It can be done with RNPermissions.requestNotifications method

0
ilies Ould menouer On

For iOS I use requestNotifications from react-native-permissions as follow:

import { requestNotifications } from "react-native-permissions";


  const requestNotificationPermissions = async () => {
    try {
      const { status, settings } = await requestNotifications([
        "alert",
        "badge",
        "sound",
      ]);
      console.log("Notification permissions status:", status);
      console.log("Notification settings:", settings);

      if (status === "granted") {
        // Permissions granted, you can proceed with your notification logic
        NotificationService.getToken();
      } else {
        // Permissions denied, handle accordingly (show a message, etc.)
        Alert.alert(
          "Permission Denied",
          "You need to enable notifications for this app."
        );
      }
    } catch (error) {
      console.error("Error requesting notification permissions:", error);
    }
  };

And call it on useEffect as follow:

  useEffect(() => {
    requestNotificationPermissions();
  }, []);

IMPORTANT NOTE: Don't forget to set NSUserNotificationsUsageDescription in ios/app_name/Info.plist:

<key>NSUserNotificationsUsageDescription</key>
<string>EXMPLE: Allow Notification to receive alert about important news!</string>

And add this to ios/app_name/PodFile

setup_permissions([
  'Notifications',
])

For Android it easy just use:

import { PermissionsAndroid } from "react-native";
PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
    );

And add this in AndroidManifest.xml:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>