expo#Notifications JavaScript Examples

The following examples show how to use expo#Notifications. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: register-to-push-notification.js    From firestore-chat with MIT License 6 votes vote down vote up
export default async function registerToPushNotification() {
  // Make sure app is running on physical device, since push notifs don't work on simulators
  if (Constants.isDevice) {
    const { status: existingStatus } = await Permissions.getAsync(
      Permissions.NOTIFICATIONS
    )
    let finalStatus = existingStatus
    if (existingStatus !== 'granted') {
      const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS)
      finalStatus = status
    }
    if (finalStatus !== 'granted') {
      return Promise.reject(
        'Failed to get expo push token for push notification!'
      )
    } else {
      // On Android, we need to specify a channel. Find out more  details at expo notification documentation
      if (Platform.OS === 'android') {
        Notifications.createChannelAndroidAsync('default', {
          name: 'default',
          sound: true,
          priority: 'max',
          vibrate: [0, 250, 250, 250],
        })
      }

      return Notifications.getExpoPushTokenAsync()
    }
  }
}
Example #2
Source File: ExpoMobileApp.js    From expo-notifications-tool with MIT License 6 votes vote down vote up
registerForPushNotifications = async () => {
  const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
  if (status !== 'granted') {
    alert('No notification permissions!');
    return;
  }

  // Get the token that identifies this device
  let token = await Notifications.getExpoPushTokenAsync();

  // POST the token to your backend server from where you can retrieve it to send push notifications.
  return fetch(PUSH_ENDPOINT, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      token: {
        value: token,
      }
    }),
  });
}
Example #3
Source File: ContactSellerForm.js    From Done-With-It with MIT License 6 votes vote down vote up
function ContactSellerForm({ listing }) {
	const handleSubmit = async ({ message }, { resetForm }) => {
		Keyboard.dismiss();

		const result = await messagesApi.send(message, listing.id);

		if (!result.ok) {
			console.log("Error", result);
			return Alert.alert(
				"Error",
				"Could not send the message to the seller."
			);
		}

		resetForm();

		Notifications.presentLocalNotificationAsync({
			title: "Awesome!",
			body: "Your message was sent to the seller.",
		});
	};

	return (
		<Form
			initialValues={{ message: "" }}
			onSubmit={handleSubmit}
			validationSchema={validationSchema}
		>
			<FormField
				maxLength={255}
				multiline
				name="message"
				numberOfLines={3}
				placeholder="Message..."
			/>
			<SubmitButton title="Contact Seller" />
		</Form>
	);
}
Example #4
Source File: Notifications.js    From Legacy with Mozilla Public License 2.0 4 votes vote down vote up
export default function SettingsScreen({ navigation }) {
  var {t} = useTranslation();
  var logins = useSelector(i=>i.logins);
  var themes = useSelector(i=>i.themes);
  var theme = useSelector(i=>i.themes[i.theme]);
  var dispatch = useDispatch();
  var {width,height} = useDimensions().window;

  var [push,setPush] = React.useState(null);
  var [data,setData] = React.useState(false);
  async function enableNotifications() {
    try {
      if (Constants.isDevice && Platform.OS !== "web") {
        const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
        let finalStatus = existingStatus;
        if (existingStatus !== 'granted') {
          const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
          finalStatus = status;
        }
        if (finalStatus !== 'granted') {
          alert('Failed to get push token for push notification!');
          return;
        }
        token = await Notifications.getExpoPushTokenAsync();
        setPush(token);
      } else {
        setPush(false);
      }

      if (Platform.OS === 'android') {
        Notifications.createChannelAndroidAsync('default', {
          name: 'default',
          sound: true,
          priority: 'max',
          vibrate: [0, 250, 250, 250],
        });
      }
    } catch(e) {
      setPush(false);
    }
  }
  async function getCurrentOptions() {
    var d = await fetch('https://server.cuppazee.app/notifications/get', {
      method: 'POST',
      body: JSON.stringify({
        token: push,
        from: FROM,
        access_token: token
      })
    })
    var {data:da} = await d.json();
    setData(Object.assign({
      token: push,
      munzee_blog: false,
      ...(da||{})
    }));
  }
  async function saveCurrentOptions() {
    setData(false)
    var d = await fetch('https://server.cuppazee.app/notifications/signup', {
      method: 'POST',
      body: JSON.stringify({
        data: JSON.stringify(data),
        from: FROM,
        access_token: token
      })
    })
    var da = await d.json();
    console.log(da);
    setData(da.data);
  }
  React.useEffect(()=>{
    enableNotifications()
  },[]);
  React.useEffect(()=>{
    if(push) {
      getCurrentOptions();
    }
  },[push]);

  if(Platform.OS==="web") return <View style={{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:theme.page.bg}}>
    <Text>{t('notifications:unavailable_web')}</Text>
  </View>

  if(push===false||data===null) return <View style={{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:theme.page.bg}}>
    <Text>{t('notifications:unavailable_generic')}</Text>
  </View>

  if(push===null||data===false) return <View style={{flex:1,justifyContent:"center",alignItems:"center",backgroundColor:theme.page.bg}}>
    <ActivityIndicator size="large" color={theme.page.fg} />
  </View>
  return (
    <View style={{ flex: 1, backgroundColor: theme.page.bg, justifyContent: 'center', alignItems: 'center' }}>
      <View style={{flex: 1, width:width>800?"50%":"100%",padding:4}}>
        <Card noPad>
          <ScrollView contentContainerStyle={{padding:8}}>
            {/* <Text allowFontScaling={false} style={{color:theme.page_content.fg,...font()}}>Push: {push||'Disabled'}</Text> */}
            <View style={{flexDirection:"row",alignItems:"center"}}>
              <Text allowFontScaling={false} style={{color:theme.page_content.fg,...font("bold")}}>{t('notifications:munzee_blog')}</Text>
              <Switch color={theme.page_content.fg} value={data.munzee_blog} onValueChange={(value)=>setData({
                ...data,
                munzee_blog: value
              })} />
            </View>
            <Button mode="contained" color="green" onPress={saveCurrentOptions}>{t('notifications:save')}</Button>
          </ScrollView>
        </Card>
      </View>
    </View>
  );
}
Example #5
Source File: AuthScreen.js    From SocialApp-React-Native with MIT License 4 votes vote down vote up
AuthScreen = (props) => {

    const [isSignup, setIsSignUp] = useState(false);
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const [isLoading, setIsLoading] = useState(false);

    const [expoPushToken, setExpoPushToken] = useState('');
    const [notification, setNotification] = useState({});

    const dispatch = useDispatch();
    let token;
    let _notificationSubscription;

    const registerForPushNotificationsAsync = async () => {
        if (Constants.isDevice) {
            const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
            let finalStatus = existingStatus;
            if (existingStatus !== 'granted') {
                const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
                finalStatus = status;
            }
            if (finalStatus !== 'granted') {
                Alert.alert(
                    'Failed !',
                    'Failed to get push token for push notification!',
                    [{ text: 'Okay' }]
                );
                return;
            }
            try{
                token = await Notifications.getExpoPushTokenAsync();
            } catch(err){
                showMessage({
                    message: `ERROR - ${err.message}`,
                    description: `${err}`,
                    type: "danger",
                    icon: { icon: "danger", position: 'left' },
                    duration: 3000
                });
            }
            console.log(token);
            setExpoPushToken(token);
        } else {
            Alert.alert(
                'Error !',
                'Must use physical device for Push Notifications',
                [{ text: 'Okay' }]
            )
        }
        if (Platform.OS === 'android') {
            Notifications.createChannelAndroidAsync('default', {
                name: 'default',
                sound: true,
                priority: 'max',
                vibrate: [0, 250, 250, 250],
            });
        }
    };

    useEffect(() => {
        registerForPushNotificationsAsync();
        console.log(expoPushToken);
        _notificationSubscription = Notifications.addListener(_handleNotification);
    }, [])
        

    const _handleNotification = notification => {
        Vibration.vibrate();
        setNotification(notification);
    };






    const validateAuthForm = () => {
        const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        const passwordRegex = /\d/
        if(isSignup && !name){
            showMessage({
                message: "Please enter a valid name.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(isSignup && name && name.length < 2){
            showMessage({
                message: "Please enter a valid name.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(!emailRegex.test(email.toLowerCase())){
            showMessage({
                message: "Please enter a valid email.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(!password || password.length === 0){
            showMessage({
                message: "Please enter your password.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        if(isSignup && password.length < 6){
            showMessage({
                message: "Password should be atleast 6 characters long.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;

        }
        if(isSignup && !passwordRegex.test(password)){
            showMessage({
                message: "Password should contain atleast 1 number.",
                type: "danger",
                icon: { icon: "danger", position: 'left' },
                duration: 3000
            });
            setIsLoading(false);
            return false;
        }
        return true;
    }


    const AuthHandler = async () => {
        setIsLoading(true);
        if(validateAuthForm()){
            if(isSignup){
                try {
                    const msg = await dispatch(authActions.signup(name, email, password, expoPushToken))
                    showMessage({
                        message: "Signup Success",
                        description: 'Please Login !',
                        type: "success",
                        icon: { icon: "success", position: 'left' },
                        duration: 3000
                    });
                    setIsSignUp(false);
                    setName('');
                    setEmail('');
                    setPassword('');
                } catch (error) {
                    showMessage({
                        message: error.message,
                        type: "danger",
                        icon: { icon: "danger", position: 'left' },
                        duration: 3000
                    });
                }
                setIsLoading(false);
            } else {
                try {
                    await dispatch(authActions.signin(email, password, expoPushToken))
                    showMessage({
                        message: "Signed in success",
                        type: "success",
                        icon: { icon: "success", position: 'left' },
                        duration: 3000
                    });
                } catch (error) {
                    showMessage({
                        message: error.message,
                        type: "danger",
                        icon: { icon: "danger", position: 'left' },
                        duration: 3000
                    });
                    setIsLoading(false);
                }
            }
        }
    };

    const inputChangeHandler = (text,inputField) => {
        if(inputField === 1){
            setName(text)
        } else if(inputField === 2){
            setEmail(text)
        } else if(inputField === 3){
            setPassword(text)
        }
    }


    return (
            <View style={styles.container}>
                <Image style={styles.bgImage} source={require('../../assets/bg-auth.png')} />
                <View style={styles.titleContainer} >
                    <Text style={styles.title}>SocialApp</Text>
                </View>

                {/* { error !== null && (
                    <View style={styles.errorMsgContainer} >
                        <Image style={styles.msgIcon} source={{ uri: "https://i.imgur.com/GnyDvKN.png" }} />
                        <Text style={styles.msgText}> {error} </Text>
                    </View>
                )} */}

                { isSignup && (
                    <View style={styles.inputContainer}>
                        <TextInput style={styles.inputs}
                            placeholder="Name"
                            underlineColorAndroid='transparent'
                            value={name}
                            onChangeText={(text) => inputChangeHandler(text,1)}
                        />
                        <Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/nolan/40/000000/name.png' }} />
                    </View>
                ) }
                
                <View style={styles.inputContainer}>
                    <TextInput style={styles.inputs}
                        placeholder="Email"
                        keyboardType="email-address"
                        underlineColorAndroid='transparent'
                        value={email}
                        onChangeText={(text) => inputChangeHandler(text, 2) }
                    />
                    <Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/nolan/40/000000/email.png' }} />
                </View>

                <View style={styles.inputContainer}>
                    <TextInput style={styles.inputs}
                        placeholder="Password"
                        secureTextEntry={true}
                        underlineColorAndroid='transparent'
                        value={password}
                        onChangeText={(text) => inputChangeHandler(text, 3) }
                    />
                    <Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/nolan/40/000000/key.png' }} />
                </View>

                <TouchableOpacity 
                    onPress={() => props.navigation.navigate('ForgotPassword')}
                    style={styles.btnForgotPassword} 
                >
                    <Text style={styles.btnText}>Forgot your password?</Text>
                </TouchableOpacity>

                <TouchableOpacity 
                    style={[styles.buttonContainer, styles.loginButton]}
                    onPress={AuthHandler}
                >

                    { isLoading ? (
                        <ActivityIndicator size="small" color="#fff" />
                    )  :(
                        <Text style={styles.loginText}>
                            { isSignup ? "Register" : "Login" }
                        </Text>
                    ) }
                    
                </TouchableOpacity>


                <TouchableOpacity 
                    style={[styles.buttonContainer, styles.registerButton]}
                    onPress={() => {
                        setIsSignUp(prevState => !prevState);
                    }}
                >
                    <Text style={styles.btnText} >
                        { isSignup ? "Already a user ? Login" : "Don't have an account ? Register" }
                    </Text>
                </TouchableOpacity>
            </View>    
    );
}