[따라하며 배우는 리액트 네이티브 기초] 섹션 8 - ios 알림 기능

posinity·2023년 7월 5일
0

라이브러리 설치

npm i @react-native-community/push-notification-ios --save
npx pod-install

깃허브에 나와있는 설치방법 따라가기

https://github.com/react-native-push-notification/ios

AppDelegate.h 파일 수정

command + shift + P 누르고 백스페이스 한번 눌러 파일을 찾는다

#import <UserNotifications/UNUserNotificationCenter.h> //추가
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate> // 수정

@end

AppDelegate.mm 파일 수정

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>

#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"ReactNativeInstaApp";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};

  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}

// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
 [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
 [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler
{
  [RNCPushNotificationIOS didReceiveNotificationResponse:response];
}


- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

/// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
///
/// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
/// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
/// @return: `true` if the `concurrentRoot` feature is enabled. Otherwise, it returns `false`.
- (BOOL)concurrentRootEnabled
{
  return true;
}



@end

xcode 설정 변경

xcode 열기 실패하면 아래 글 참고
[에러] xcode에서 React Native프로젝트가 안열리는 현상 (Could not open file 에러)

background Modes 변경

Signing & Capabilities > + 버튼 클릭

remote notifications 클릭

Push Notofications 클릭

Signing & Capabilities > + 버튼 클릭

클릭만 해놓기

index.js 변경

/**
 * @format
 */

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios'; // 추가

PushNotification.configure({
  onNotification: function (notification) {
    console.log('notification', notification);

    notification.finish(PushNotificationIOS.FetchResult.NoData); //추가
  },
  popInitialNotification: true,
  requestPermissions: Platform.OS === 'ios',
});

AppRegistry.registerComponent(appName, () => App);

ios 분기처리 코드 추가

/// PostItem.js
...
import PushNotificationIOS from '@react-native-community/push-notification-ios'; /// 추가

const PostItem = ({data}) => {
  const [like, setLike] = useState(data.isLiked);

  const handleNotification = title => {
    if (Platform.OS === 'ios') { /// ios 코드 추가
      PushNotificationIOS.addNotificationRequest({
        id: title,
        title: `${title}을 클릭했습니다.`,
        body: `메세지 입니다.`,
      });
    } else { // 기존에 작성한 안드로이드 부분 여기 넣기
      PushNotification.cancelAllLocalNotifications();

      PushNotification.localNotificationSchedule({
        channelId: 'insta-channel',
        title: `${title}를 클릭했습니다.`,
        message: `메시지 입니다.`,
        color: 'red',
        date: new Date(Date.now() + 5 * 1000),
        allowWhileIdle: true,
      });
    }
  };

제대로 되는지 확인

npx react-native start > i

여기서 나는 에러나서 다른 강의로 넘어간다..;

profile
문제를 해결하고 가치를 제공합니다

0개의 댓글