【问题标题】:Local Push Notification not working on iOS, using React Native本地推送通知在 iOS 上不起作用,使用 React Native
【发布时间】:2021-11-06 21:22:53
【问题描述】:

我无法使用 React Native 让本地 iOS 推送通知正常工作。我检查了类似的线程,但无法找到答案。这是(应该是)一个基本设置,所以希望有人能提供帮助。

我正在尝试在按下包含在 FlatList 中的 TouchableOpacity 对象时触发推送通知。我没有收到任何代码错误,只是没有触发通知。

我已经按照文档安装了两个 npm 包,并且我正在使用 React Native v0.65.1:-

npm install --save react-native-push-notification
npm i @react-native-community/push-notification-ios --save 

我在下面添加了我的代码。还有其他文件与应用程序上的其他功能相关联,但我没有在此处包含它们,因为这是唯一包含推送通知支持代码的文件。

我哪里出错了?

提前谢谢...


import {Alert, FlatList, Pressable, StyleSheet, Text, TextInput, TouchableOpacity, View} from "react-native";
import React, { useEffect, useState } from "react";
import GlobalStyle from '../utils/GlobalStyle';
import CustomButton from "../utils/CustomButton";
import SQLite from "react-native-sqlite-storage";
import { useDispatch, useSelector } from "react-redux";
import { setAge, setName, increaseAge, getCities } from "../redux/actions";
import PushNotification from "react-native-push-notification";
import PushNotificationIOS from "@react-native-community/push-notification-ios";

// store sqlite open database function
const db = SQLite.openDatabase(
    { name: 'sqlite_db', location: 'default' },
    () => {},
    error => { console.log(error) }
);

export default function Home({ navigation, route }) {

  // replace local state objects with global redux objects
  const { name, age, cities } = useSelector(state => state.userReducer);
  const dispatch = useDispatch();

  // function calls for SQLite and api data fetch
  useEffect(() => {
      getData();
      dispatch(getCities());
  }, []); 

  // fetch data objects from SQLite store
  const getData = () => {
      try {
          db.transaction((tx) => {
              tx.executeSql(
                  'SELECT Name, Age FROM Users',
                  [],
                  (tx, results) => {
                      let length = results.rows.length;
                      if (length > 0) {
                          let userName = results.rows.item(0).Name;
                          let userAge = results.rows.item(0).Age;
                          dispatch(setName(userName));
                          dispatch(setAge(userAge));
                      }
                  }
              )
          })
      } catch (error) {
          console.log(error);
      }
  }

  // function to update SQLite data store
  const updateData = async () => {
      if (name.length == 0) {
          Alert.alert('WARNING!', 'Please enter your name')
      } else {
          try {
              db.transaction((tx) => {
                  tx.executeSql(
                      'UPDATE Users SET Name=?',
                      [name],
                      () => {
                          Alert.alert('SUCCESS!', 'Your data has been updated')
                      },
                      error => { console.log(error) }
                  )
              })
          } catch (error) {
              console.log(error)
          }
      }
  }

  // function to remove data from SQLite data store
  const removeData = async () => {
      try {
          db.transaction((tx) => {
              tx.executeSql(
                  "DELETE FROM Users",
                  [],
                  () => {
                      navigation.navigate('Login')
                  },
                  error => { console.log(error) }
              )
          })

      } catch (error) {
          console.log(error)
      }
  }

  **object to store function, fired when touchable is clicked
  bound to touchable opacity onPress**

  const handleNotification = (item) => {
      PushNotification.localNotification({
          title: 'Push Notification',
          message: 'You clicked on' + item.country
      })
  }

  return(
      <View style={styles.body}>
          <Text style={[
              GlobalStyle.header,
              GlobalStyle.text
          ]}>
              Welcome {name} !
          </Text>

          **flatlist used to display api fetch responses
          push notification onPress function is bound to TouchableOpacity object**

          <FlatList
              data={cities}
              renderItem={({item}) => (
                  <TouchableOpacity
                      onPress={() => { handleNotification(item) }}
                  >
                      <View style={styles.item}>
                          <Text style={styles.title}>{item.country}</Text>
                          <Text style={styles.subtitle}>{item.city}</Text>
                      </View>
                  </TouchableOpacity>
              )}
              keyExtractor={(item, index) => index.toString()}
          />
      </View>
  )
}

const styles = StyleSheet.create({
  body: {
    flex: 1,
    // justifyContent: 'center',
    alignItems: 'center',
  },
  // now obsolete, as we have replaced this with a global style
  text: {
    // fontWeight: 'bold',
    // fontSize: 26,
    margin: 10,
    // fontFamily: 'TitilliumWeb-Bold'
  },
  navButton: {
    borderRadius: 11,
    paddingHorizontal: 20,
    width: 180,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center'
  },
  openDrawerButton: {
    borderRadius: 11,
    paddingHorizontal: 20,
    width: 180,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10
  },
  thirdFont: {
    fontSize: 18,
    paddingTop: 20,
    fontFamily: 'Roboto-Regular'
  },
  textInput: {
    width: 250,
    height: 50,
    marginTop: 10,
    borderRadius: 10,
    backgroundColor: '#d9cbe7',
      borderWidth: 2,
      borderColor: '#d9c1c1',
    textAlign: 'center',
    fontSize: 20
  },
  item: {
      backgroundColor: 'white',
      borderWidth: 3,
      borderColor: '#bfcab8',
      borderRadius: 7,
      margin: 7,
      width: 350,
      justifyContent: 'center',
      alignItems: 'center',
      paddingVertical: 10
  },
    title: {
      fontSize: 20,
      fontFamily: 'Ubuntu-Bold',
      color: '#a03f3f'
    },
    subtitle: {
      marginTop: 8,
      fontFamily: 'Ubuntu-Regular',
      fontSize: 16
    }
})

【问题讨论】:

    标签: ios react-native push-notification


    【解决方案1】:
    import PushNotificationIOS from "@react-native-community/push-notification-ios";
    
    export default class NotifService {
    
      constructor(onRegister, onNotification) {
        this.configure(onRegister, onNotification);
    
        this.lastId = 0;
      }
    
      configure(onRegister, onNotification, gcm = "") {
        PushNotificationIOS.configure({
          // (optional) Called when Token is generated (iOS and Android)
          onRegister: onRegister, //this._onRegister.bind(this),
    
          // (required) Called when a remote or local notification is opened or received
          onNotification: onNotification, //this._onNotification,
    
          // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
          senderID: gcm,
    
          // IOS ONLY (optional): default: all - Permissions to register.
          permissions: {
            alert: true,
            badge: true,
            sound: true
          },
    
          // Should the initial notification be popped automatically
          // default: true
          popInitialNotification: true,
    
          /**
            * (optional) default: true
            * - Specified if permissions (ios) and token (android and ios) will requested or not,
            * - if not, you must call PushNotificationsHandler.requestPermissions() later
            */
          requestPermissions: true,
        });
      }
    
      localNotif(title, message, sound, color) {
        this.lastId++;
        PushNotificationIOS.localNotificationSchedule({
          /* Android Only Properties */
          id: ''+this.lastId, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
          ticker: "My Notification Ticker", // (optional)
          autoCancel: true, // (optional) default: true
          largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
          smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
          bigText: message, // (optional) default: "message" prop
          color: color, // (optional) default: system default
          vibrate: true, // (optional) default: true
          vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
          tag: 'some_tag', // (optional) add tag to message
          group: "group", // (optional) add group to message
          ongoing: false, // (optional) set whether this is an "ongoing" notification
    
          /* iOS only properties */
          alertAction: 'view', // (optional) default: view
          category: '', // (optional) default: null
          userInfo: {}, // (optional) default: null (object containing additional notification data)
    
          /* iOS and Android properties */
          title: title, // (optional)
          message: message, // (required)
          playSound: sound, // (optional) default: true
          soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
          actions: '["Yes", "No"]',  // (Android only) See the doc for notification actions to know more
        });
      }
    
      checkPermission(cbk) {
        return PushNotification.checkPermissions(cbk);
      }
    
      cancelNotif() {
        console.log(this.lastId, "***")
        PushNotification.cancelLocalNotifications({id: ''+this.lastId});
      }
    
      cancelAll() {
        PushNotification.cancelAllLocalNotifications();
      }
    }
    

    【讨论】:

    • 谢谢@Shivo'ham 0。试过了,似乎没有用。我现在遇到构建错误,并显示以下消息 'React/RCTPushNotificationManager.h' file not found #import
    • 将此添加到 Podfile pod 'React-RCTPushNotification', :path => '../node_modules/react-native/Libraries/PushNotificationIOS'
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多