본문 바로가기

React-native/notification

[ React Native ] 무음 진동 상관없이 커스텀 사운드로 푸시알림

개발환경

System:
    OS: macOS 12.6
    CPU: (8) arm64 Apple M1
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 19.4.0 - /opt/homebrew/bin/node
    npm: 9.2.0 - /opt/homebrew/bin/npm
    Watchman: 2023.01.09.00 - /opt/homebrew/bin/watchman
  Managers:
    CocoaPods: 1.11.3 - /opt/homebrew/bin/pod
  IDEs:
    Android Studio: 2021.1 AI-211.7628.21.2111.8309675
    Xcode: 14.0.1/14A400 - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.17 - /usr/bin/javac
  npmPackages:
    react: 18.1.0 => 18.1.0 
    react-native: 0.70.6 => 0.70.6 

 

이전 푸시알림 설정

2023.01.18 - [React-native] - [REACT-NATIVE] 백그라운드에서 헤드업 푸시

 

[REACT-NATIVE] 백그라운드에서 헤드업 푸시

참고한 사이트 https://github.com/zo0r/react-native-push-notification https://github.com/react-native-push-notification/ios GitHub - zo0r/react-native-push-notification: React Native Local and Remote Notifications React Native Local and Remote Notific

ican-do.tistory.com

 

2023.01.18 - [React-native] - [ React Native ] 푸시 알림 시 커스텀 사운드 적용

 

[ React Native ] 푸시 알림 시 커스텀 사운드 적용

개발환경 System: OS: macOS 12.6 CPU: (8) arm64 Apple M1 Shell: 5.8.1 - /bin/zsh Binaries: Node: 19.4.0 - /opt/homebrew/bin/node npm: 9.2.0 - /opt/homebrew/bin/npm Watchman: 2023.01.09.00 - /opt/homebrew/bin/watchman Managers: CocoaPods: 1.11.3 - /opt/h

ican-do.tistory.com

 

이번에 사용할 라이브러리는 

react-native-sound-player  사운드 플레이어 입니다.

사운드 플레이어 라이브러리 설치 

$ npm i react-native-sound-player

$ cd ios && pod install && cd ..

 

1. 사운드 파일 설정

위에 2번째 링크 참고

 

2. 사운드 플레이 코드

try {
      SoundPlayer.loadSoundFile('sound_file', 'mp3');
      SoundPlayer.play();
} catch (e) {
      console.log(`cannot play the sound file`, e);
}

 

 

3. 백그라운드 알림 시

Index.js 파일에서 setBackgroundMessageHandler 메서드 안에 추가

 

4. 실행중인 앱에서 알림 시

app.js 안에 푸시알림을 담당하는 onMessage 안에 코드 추가

// 푸쉬 알림
  useEffect(() => {
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      // 테스트
      // Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
      console.log('foreground noti', JSON.stringify(remoteMessage));
      
      // 조건문의 경우는 소리를 내는 푸시를 구분하기 위함 테스트 할때는 조건문 없이 해도됨
      if (remoteMessage.data.push_type === 'test') {
        console.log('\n\n사운드 정상 작동');
        try {
          SoundPlayer.loadSoundFile('sound_file', 'mp3');
          SoundPlayer.play();
        } catch (e) {
          console.log(`cannot play the sound file`, e);
        }
      }
    });

    return unsubscribe;
  }, []);

 

푸시 알림에 따라 소리가 잘 나오는 것을 확인할수 있습니다 :)

 

iOS 재생 관련 경고

소리재생이 안되는 경우 참고하세요

2023.01.19 - [React-native] - [ React Native ] Sending "FinishedLoading" with no listeners registered. 경고 해결