Browse Source

Puedo guardar el push token en la DB

ErnestoOrtiz2 2 years ago
parent
commit
a7c7086efd
3 changed files with 1312 additions and 8 deletions
  1. 1182
    3
      package-lock.json
  2. 3
    1
      package.json
  3. 127
    4
      screens/main/Home_page.js

+ 1182
- 3
package-lock.json
File diff suppressed because it is too large
View File


+ 3
- 1
package.json View File

@@ -26,7 +26,9 @@
26 26
     "react-redux": "^7.2.5",
27 27
     "redux": "^4.1.1",
28 28
     "redux-thunk": "^2.3.0",
29
-    "react-native-safe-area-context": "3.2.0"
29
+    "react-native-safe-area-context": "3.2.0",
30
+    "expo-notifications": "~0.12.3",
31
+    "expo-constants": "~11.0.1"
30 32
   },
31 33
   "devDependencies": {
32 34
     "@babel/core": "^7.9.0"

+ 127
- 4
screens/main/Home_page.js View File

@@ -1,4 +1,4 @@
1
-import React, {useState, useEffect} from 'react'
1
+import React, {useState, useEffect, useRef} from 'react'
2 2
 import { Button, Text, View, StyleSheet} from 'react-native'
3 3
 import {FlatList, ListViewBase } from 'react-native'
4 4
 import {TouchableOpacity} from 'react-native-gesture-handler'
@@ -12,13 +12,41 @@ import { connect } from 'react-redux'
12 12
 import { bindActionCreators } from 'redux' 
13 13
 import { fetchUser } from '../../redux/actions/index'
14 14
 
15
+import Constants from 'expo-constants';
16
+import * as Notifications from 'expo-notifications';
17
+
18
+Notifications.setNotificationHandler({
19
+  handleNotification: async () => ({
20
+    shouldShowAlert: true,
21
+    shouldPlaySound: true,
22
+    shouldSetBadge: false,
23
+  }),
24
+});
25
+
26
+
15 27
 export function Home_page({navigation}) {
16 28
   const [threads, setThreads] = useState([]);  
17 29
   const [loading, setLoading] = useState(true);
18 30
   
19 31
   const [roomName, setRoomName] = useState('');
20 32
 
33
+
34
+
35
+  const [expoPushToken, setExpoPushToken] = useState('');
36
+  const [notification, setNotification] = useState(false);
37
+  const notificationListener = useRef();
38
+  const responseListener = useRef();
39
+
40
+
21 41
   useEffect(() => {
42
+    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
43
+    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
44
+      setNotification(notification);
45
+    });
46
+
47
+    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
48
+      console.log(response);
49
+    });
22 50
 
23 51
     const fire = firebase.firestore()
24 52
     .collection('THREADS')
@@ -41,14 +69,37 @@ export function Home_page({navigation}) {
41 69
 
42 70
     });
43 71
 
44
-    return () => fire();
72
+    //return () => fire();
73
+    return () => {
74
+      Notifications.removeNotificationSubscription(notificationListener.current);
75
+      Notifications.removeNotificationSubscription(responseListener.current);
76
+      fire();
77
+    }
45 78
   }, []);
46 79
   
47 80
   if (loading) {
48 81
     return <Loading />;
49 82
   }
50 83
 
84
+  const sendMessage = (token) => {
85
+    fetch('https://exp.host/--/api/v2/push/send', {
86
+      method: 'POST',
87
+      headers: {
88
+        Accept: 'application/json',
89
+        'Accept-encoding': 'gzip, deflate',
90
+        'Content-type': 'application/json',
91
+      },
92
+      body: JSON.stringify({
93
+        to: token,
94
+        title: 'Ernesto',
95
+        body: 'Freehand message',
96
+        data: { data: 'goes here' },
97
+        _displayInForeground: true,
98
+      }),
99
+    });
100
+  }
51 101
 
102
+  
52 103
   function handleButtonPress() {
53 104
       firebase.firestore()
54 105
         .collection('THREADS')
@@ -84,7 +135,18 @@ export function Home_page({navigation}) {
84 135
           </TouchableOpacity>
85 136
         )}
86 137
         />
87
-        
138
+      <Text>Your expo push token: {expoPushToken}</Text>
139
+      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
140
+        <Text>Title: {notification && notification.request.content.title} </Text>
141
+        <Text>Body: {notification && notification.request.content.body}</Text>
142
+        <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
143
+      </View>
144
+      <Button
145
+        title="Press to Send Notification"
146
+        onPress={async () => {
147
+          await sendPushNotification(expoPushToken);
148
+        }}
149
+      /> 
88 150
       <Button
89 151
         title='CrearChat'
90 152
         onPress={() => handleButtonPress()}
@@ -93,13 +155,74 @@ export function Home_page({navigation}) {
93 155
         title ='Hacer Busqueda'
94 156
         onPress= {() => navigation.navigate('Search')}
95 157
       />
158
+      <Button
159
+        title ='Logout'
160
+        onPress= {() => firebase.auth().signOut()}
161
+      />
162
+      <Button
163
+        title ='SendMessage'
164
+        onPress= {() => sendMessage(expoPushToken)}
165
+      />
96 166
         </ImageBackground>
97 167
     );
98 168
   }
169
+// Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
170
+async function sendPushNotification(expoPushToken) {
171
+  const message = {
172
+    to: expoPushToken,
173
+    sound: 'default',
174
+    title: 'Original Title',
175
+    body: 'And here is the body!',
176
+    data: { someData: 'goes here' },
177
+  };
178
+
179
+  await fetch('https://exp.host/--/api/v2/push/send', {
180
+    method: 'POST',
181
+    headers: {
182
+      Accept: 'application/json',
183
+      'Accept-encoding': 'gzip, deflate',
184
+      'Content-Type': 'application/json',
185
+    },
186
+    body: JSON.stringify(message),
187
+  });
188
+}
189
+
190
+async function registerForPushNotificationsAsync() {
191
+  let token;
192
+  if (Constants.isDevice) {
193
+    const { status: existingStatus } = await Notifications.getPermissionsAsync();
194
+    let finalStatus = existingStatus;
195
+    if (existingStatus !== 'granted') {
196
+      const { status } = await Notifications.requestPermissionsAsync();
197
+      finalStatus = status;
198
+    }
199
+    if (finalStatus !== 'granted') {
200
+      alert('Failed to get push token for push notification!');
201
+      return;
202
+    }
203
+    token = (await Notifications.getExpoPushTokenAsync()).data;
204
+    console.log(token);
205
+  } else {
206
+    alert('Must use physical device for Push Notifications');
207
+  }
208
+
209
+  if (Platform.OS === 'android') {
210
+    Notifications.setNotificationChannelAsync('default', {
211
+      name: 'default',
212
+      importance: Notifications.AndroidImportance.MAX,
213
+      vibrationPattern: [0, 250, 250, 250],
214
+      lightColor: '#FF231F7C',
215
+    });
216
+  }
217
+
218
+  firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
219
+  return token;
220
+}
221
+
99 222
 
100 223
 const mapStateToProps = (store) => ({
101 224
   currentUser: store.userState.currentUser
102 225
 })
103 226
 const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
104 227
 
105
-export default connect(mapStateToProps, mapDispatchProps)(Home_page);
228
+export default connect(mapStateToProps, mapDispatchProps)(Home_page);