There are a few steps to follow before receiving notifications on iOS. And by the way, it’s the same for MacOS.
Open the Runner.xcworkspace file with XCode. Next, select the “Signing and capabilities” tab. Click on the “+ Capabilities” button: this allows you to add a new capability for your app. From there type push on the search box and select push notifications.
Now let’s repeat the process for “BackGround modes”: so Click on the “+ Capabilities” button, and search for “Background Modes”. From there enable Background fetch and Remote notifications. OK, this completes the XCOde part. Now we need to get back to our Flutter project.
On iOS, users won’t receive notifications before they explicitly grant your app a specific permission. By the way, the same is true on the web. The good news is that you can easily ask for the permission, using the Firebase Messaging instance requestPermission method.
So in the main method, after declaring the FirebaseMessaging instance, declare another final, called notificationSettings. This awaits the messaging requestPermission method. And here we can set several parameters:
Let’s set alert to true: with this you are requesting the permission to display alerts. Set badge to true: this is to update your app’s badge, and also set sound to true, to play a sound when users receive the message.
There are several other properties that you can set: if you ctrl+click on the requestPermission method you’ll see the other settings that you can setfor your notifications.
final notificationSettings = await messaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
Right, now that we have asked our user the permission, let’s print the authorization status on the console: this can take three values: granted, declined or not determined.
print('Notification permission status: '
+ '${notificationSettings.authorizationStatus}');
The first time you run your app, its status will be “not determined”, and it’s the only condition where users will see the message that asks the permission.
If your user declines the permission request, the requestPermission method will always return “declined”, without displaying any message, and your app won’t receive any notification: the only way to enable notifications will be from the device Settings app, where users can choose the permissions for every app.
If users grant the permission, they’ll only have to grant it once. From then on, they’ll always receive notifications when you send them. Note that this procedure works on iOS, macOS and the web. OK, let’s run the app.
As you can see, you are asked for the permission to receive messages. Let’s grant it so we can finally test whether your app receives notifications from Firebase.