티스토리 뷰

전 글에서 RN 에 푸쉬를 추가해 보았다. https://jamcode.tistory.com/77

 

React Native Push 사용하기(React Native + Push + AWS SNS)

몇 년전 iOS 푸쉬를 사용하고 암 투병생활을 좀 해서 다시는 하고 싶지 않았다. 하지만 회사에서 다시 해야만 하는 상황이 생겼고 이 번에는 React Native(이하 RN) 환경에서 구축하게 되었다. 다행히 암(Push 설..

jamcode.tistory.com

getAppleMessage, getAndroidMessage 함수에서 보내는 데이터를 만드는데 푸쉬를 보낼 때 추가 정보를 전달하고 싶을 때가 있다. 그래서 iOS 와 Android 의 추가 정보를 전달하는 코드를 공유한다. 이 코드는 위의 글에서 이어지는 내용으로 AWS 를 통해서 보낼 때의 경우이다.

// 공통 부분
Map<String, Object> messageMap = new HashMap<>();
messageMap.put("default", message);
messageMap.put(platform.name(), JSON.writeValueAsString(getPushContents()));

// iOS
Map<String, Object> getPushContents() {
	Map<String, Object> appMessageMap = new HashMap<>();
	appMessageMap.put("alert", getMessage());
	appMessageMap.put("badge", getBadge());
	appMessageMap.put("sound", "default");

	Map<String, Object> appleMessageMap = new HashMap<>();
	appleMessageMap.put("aps", appMessageMap);
	appleMessageMap.put("extra", new HashMap<String, Object>()); // 이 부분 추가 정보

	return appleMessageMap;
}

// android
Map<String, Object> getPushContents() {
	Map<String, Object> data = new HashMap<>();
	data.put("message", getMessage());
	data.put("extra", new HashMap<String, Object>()); // 이 부분 추가 정보

	Map<String, Object> androidMessageMap = new HashMap<>();
	androidMessageMap.put("data", data);
	return androidMessageMap;
}

주석 부분에 추가 정보를 입력하고 전 글에서 추가 했던 react-native-push-notification 라이브러리에서 처리를 추가로 해주면 된다.

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

                let extraData;
                if (Platform.OS === 'ios') {
                    console.log('extra data: ', notification.data.extra);
                    extraData = notification.data.extra;
                } else if (Platform.OS === 'android') {
                    console.log('extra data: ', notification.extra); // 문자열로 옴
                    extraData = JSON.parse(notification.extra);
                }

                alert(JSON.stringify(extraData)); // ios, android 같은 값이 보인다.

                // ios / android app 실행 중 push 를 에서 받았을 때
                // foreground: true, userInteraction: false,

                // ios / android app 외부에서 터치로 들어왔을 떼
                // foreground: false, userInteraction: true

                // process the notification
                // required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
                if (Platform.OS === 'ios') {
                    notification.finish(PushNotificationIOS.FetchResult.NoData);
                }
            },

안드로이드의 경우 extra 가 문자열로 오기 때문에 JSON.parse 를 통해서 object 로 변경해 줘야 하고 iOS 는 object로 전달된다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함