Ios Push Notification Using Aws Sns

Aws sns directly send notification to ios device , in background or kill state of app now we need the notifcation in foreground so we to do some configuration and library install to get our desired result ,

Install

     Using npm :

          npm i @react-native-community/push-notifcation-ios --save

      Using yarn :

           yarn add @react-native-community/push-notifcation-ios --save

now u have to do some configuration of above library in ios , 
         go ios folder of react native and open the folder named as your project and open a file name 
AppDelegate.
          #import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
add these above line on above ....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"App Launched with Options: %@", launchOptions);
if (![FIRApp defaultApp]) {
[FIRApp configure];
} else {
NSLog(@" Firebase already configured, skipping...");
}
[FIRConfiguration sharedInstance].loggerLevel = FIRLoggerLevelDebug;
//this below lines This gets the singleton instance of the UNUserNotificationCenter,
// which is responsible for handling all notification-related tasks
//(scheduling, delivering, managing notifications) on iOS.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//This sets the current class (self) as the delegate of the notification center.
center.delegate = self;
self.moduleName = @"name of your project";

self.initialProps = @{};
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

below further code add it no need ti change anything directly copy and paste 
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog(@" Foreground Notification Received: %@", notification.request.content.userInfo);
// Post notification to update UI if needed
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationReceived"
object:self
userInfo:userInfo];

completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}


// APNs Registration Success
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@" APNs Device Token Registered: %@", deviceToken);
[FIRMessaging messaging].APNSToken = deviceToken;
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// Received Remote Notification (App is in Background/Killed)
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(@"📩 Received Remote Notification: %@", userInfo);
[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];

completionHandler(UIBackgroundFetchResultNewData);
}

// APNs Registration Failed
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@" Failed to Register for APNs: %@", error);
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}

// User Clicked on a Notification
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
NSLog(@"User Clicked on Notification: %@", response.notification.request.content.userInfo);

}

completionHandler();
}
AppDelegate.h:
                   #import <RCTAppDelegate.h>
#import <UserNotifications/UNUserNotificationCenter.h>
#import <UIKit/UIKit.h>
@interface AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate>
@end


Now it show notification on xcode only not in react native terminal you to create a notification bridage which help you see notification terminal and perform some navigation on it .....now we are proceed to construct a bridge between ios and react native ...

AppDelegate.mm
#import <React/RCTEventEmitter.h>
#import <React/RCTBridgeModule.h>
#import "NotificationBridge.h"

// User Clicked on a Notification i add a notification bridge so that the click notifcation go
//to bridge ..
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
NSLog(@" User Clicked on Notification: %@", response.notification.request.content.userInfo);

NSDictionary *userInfo = response.notification.request.content.userInfo;
if (userInfo) {
// Get the instance of NotificationBridge
NotificationBridge *bridge = [self.bridge moduleForClass:[NotificationBridge class]];
if (bridge) {
[bridge sendNotificationToReactNative:@"NotificationClicked" withUserInfo:userInfo];
} else {
NSLog(@" NotificationBridge instance is nil, cannot send event.");
}
}

completionHandler();
}

Now code for files you have to add two files name NotificationBridge.h and NotificationBridge.m
NotificationBridge.h code :
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface NotificationBridge : RCTEventEmitter <RCTBridgeModule>

// Declare the method so it is visible to AppDelegate.mm
- (void)sendNotificationToReactNative:(NSString *)eventName withUserInfo:(NSDictionary *)userInfo;

@end
NotificationBridge.m code:
#import "NotificationBridge.h"

@implementation NotificationBridge

RCT_EXPORT_MODULE();

static NotificationBridge *sharedInstance = nil;

- (instancetype)init
{
if (self = [super init]) {
sharedInstance = self; // Store the instance
}
return self;
}

- (NSArray<NSString *> *)supportedEvents
{
return @[@"NotificationReceived", @"NotificationClicked"];
}

// Use instance method instead of class method
- (void)sendNotificationToReactNative:(NSString *)eventName withUserInfo:(NSDictionary *)userInfo
{
if (sharedInstance != nil) {
[sharedInstance sendEventWithName:eventName body:userInfo];
} else {
NSLog(@" NotificationBridge instance is nil, cannot send event.");
}
}

@end

just you have copy paste the code .... and one more important you have to add these files also
from xcode so that they properly configured and works
Now Listen code on react native app to see the console of notification on terminal...
import {NativeEventEmitter, NativeModules} from 'react-native';

useEffect(() => {
if (!NotificationBridge) {
console.error(" NotificationBridge is not available in NativeModules.");
return;
}

const eventEmitter = new NativeEventEmitter(NotificationBridge);

// Listen for Foreground Notifications
const onForegroundNotification = eventEmitter.addListener("NotificationReceived", (notification) => {
console.log(" Foreground Notification:", notification);
Alert.alert("New Notification", notification?.body || "You have a new message.");
});

// Listen for Clicked Notifications (Navigates)
const onNotificationClicked = eventEmitter.addListener("NotificationClicked", (notification) => {
console.log("Notification Clicked:", notification);
// below here you can perform navigation
});

return () => {
onForegroundNotification.remove();
onNotificationClicked.remove();
};
}, []);


Comments

Popular posts from this blog

Complete Guide to Testing React Native Applications with React Native Testing Library

Firebase Setup For Ios And Android In React Native