App.js 6.82 KB
Newer Older
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React from 'react';
import {
  StyleSheet,
  View,
  Text,
  StatusBar,
  SafeAreaView,
  Platform,
  Alert,
  Clipboard,
} from 'react-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
import firebase from 'react-native-firebase';

const setBadgesCount = badgeCount => {
  badgeCount = Number.isInteger(Number.parseInt(badgeCount, 10))
    ? Number.parseInt(badgeCount, 10)
    : 0;
  firebase.notifications().setBadge(badgeCount);
};

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  async componentDidMount() {
    if (Platform.OS === 'ios') {
      try {
        console.info('Notification[deviceToken] init');
        await firebase.messaging().ios.registerForRemoteNotifications();
        console.info('Notification[deviceToken] to do requestPermission');
        await firebase.messaging().requestPermission();
        const deviceToken = await firebase.messaging().ios.getAPNSToken();
        console.info(`Notification[deviceToken] ${deviceToken}`);
        Alert.alert('getAPNSToken', deviceToken, [
          {
            text: 'ok',
            onPress: async () => {
              await Clipboard.setString(deviceToken);
            },
          },
        ]);
      } catch (e) {
        console.error('Notification[registerForRemoteNotifications] error:', e);
      }
    } else {
      try {
        console.info('Notification[deviceToken] init');
        const enabled = await firebase.messaging().hasPermission();
        if (!enabled) {
          await firebase.messaging().requestPermission();
        }
        const deviceToken = await firebase.messaging().getToken();
        console.info(`Notification[deviceToken] ${deviceToken}`);
      } catch (e) {
        console.error('Notification[requestPermission] error:', e);
      }
    }
    this.registerNotifications();
  }

  componentWillUnmount() {
    // Unsubscribe
    if (this.notificationDisplayedListener) {
      this.notificationDisplayedListener();
    }
    if (this.notificationListener) {
      this.notificationListener();
    }
    if (this.notificationOpenedListener) {
      this.notificationOpenedListener();
    }
    // if (this.messageListener) this.messageListener();
  }

  async registerNotifications() {
    /*
     * Triggered when a particular notification has been received in foreground
     * */
    this.notificationListener = firebase
      .notifications()
      .onNotification(notification => {
        console.info('Notification[onNotification]', notification);
        const {_body, _data} = notification;
        if (_data) {
          const {badge, pushId} = _data;
          if (pushId) {
            if (badge) {
              setBadgesCount(badge);
            }
            this.handleNotification({
              badge,
              pushId,
              body: _body,
              foreground: true,
            });
          } else {
            console.error(
              'Notification[onNotification]: No Notification PushId',
            );
          }
        } else {
          console.error('Notification[onNotification]: No Notification Body');
        }
      });

    /*
     * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
     * */
    this.notificationOpenedListener = firebase
      .notifications()
      .onNotificationOpened(notificationOpen => {
        console.info('Notification[onNotificationOpened]', notificationOpen);
        const {_body, _data} = notificationOpen.notification;
        if (_data) {
          const {badge, pushId} = _data;
          if (pushId) {
            this.handleNotification({
              badge,
              pushId,
              body: _body,
              userInteraction: true,
            });
          } else {
            console.error(
              'Notification[onNotificationOpened]: No Notification PushId',
            );
          }
        } else {
          console.error(
            'Notification[onNotificationOpened]: No Notification Body',
          );
        }
      });

    /*
     * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
     * */
    const notificationOpen = await firebase
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      console.info('Notification[notificationOpen]', notificationOpen);
      const {_body, _data} = notificationOpen.notification;
      if (_data) {
        const {badge, pushId} = _data;
        if (pushId) {
          this.handleNotification({
            badge,
            pushId,
            body: _body,
            userInteraction: true,
          });
        } else {
          console.error(
            'Notification[notificationOpen]: No Notification PushId',
          );
        }
      } else {
        console.error('Notification[notificationOpen]: No Notification Body');
      }
    }

    this.notificationDisplayedListener = firebase
      .notifications()
      .onNotificationDisplayed(notification => {
        // Process your notification as required
        // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
        console.info('Notification[onNotificationDisplayed]', notification);
      });

    /*
     * Triggered for data only payload in foreground
     * */
    // this.messageListener = firebase.messaging().onMessage(message => {
    //   // process data message
    //   console.info('Notification[onMessage]', JSON.stringify(message));
    // });
  }

  /**
   * 處理推播訊息通知
   * @param {Object} notification
   */
  handleNotification(notification) {
    console.info(`handleNotification: ${JSON.stringify(notification)}`);
    const {body} = notification;
    Alert.alert('', body, [{text: 'ok'}]);
  }

  render() {
    return (
      <View style={styles.scrollView}>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView style={styles.body}>
          <Text style={styles.sectionTitle}>sample react native </Text>
        </SafeAreaView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  engine: {
    position: 'absolute',
    right: 0,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
  highlight: {
    fontWeight: '700',
  },
  footer: {
    color: Colors.dark,
    fontSize: 12,
    fontWeight: '600',
    padding: 4,
    paddingRight: 12,
    textAlign: 'right',
  },
});

export default App;