【问题标题】:Push notification in existing expo project现有世博项目中的推送通知
【发布时间】:2019-06-11 23:23:25
【问题描述】:

我在 react-native 中创建了一个现有的应用程序。在该应用程序中,我必须添加博览会推送通知功能。我使用以下链接创建了 NotificationController: https://docs.expo.io/versions/v32.0.0/guides/push-notifications

我现在需要知道我必须在哪里放置这个控制器。我是移动开发的新手,只需要有关正确放置此控制器的帮助,以便我们可以将其展示给客户。

【问题讨论】:

    标签: react-native push-notification expo


    【解决方案1】:

    创建推送通知服务后,它可以是服务目录中单个文件中的函数(如果不存在则创建),也可以是组件。

    然后将该函数导入到您的主 app.js 中,并在 componentDidMount 生命周期函数中使用它。这只是一个示例代码,我相信这可以进一步改进,但这已经足够开始了。

    push_notification.js

    import {Permissions, Notifications} from 'expo';
    import { ActivityIndicator, AsyncStorage} from 'react-native';
    
    export default async () => {
    
        try{
            let previousToken =  await AsyncStorage.getItem('pushToken');
    
            if(previousToken){
                return;
            }else{
                let {status} = await Permissions.askAsync(Permissions.NOTIFICATIONS);
                console.log(status);
    
                if(status !== 'granted'){
                    console.log("Don't like to receive push");
                }
    
                let token  = await  Notifications.getExpoPushTokenAsync();
    
                return token;
            }
        } catch(err){
            console.log(err);
        }
    };
    

    App.js

    import PushNotification from "../services/push_notifications"; 
    import axios from 'axios';
    
     async componentDidMount(){
    
         let tokenFromStorage = await zlAsyncStorage.getItem('pushToken');
         console.log('token from storage',tokenFromStorage);return;
        let token =  await  PushNotification();
        AsyncStorage.setItem('pushToken',token);
    
        console.log("here");
    
        //Save the token in couch db
        await axios({
    
          url:"http://192.168.8.148:5984/mycompany",
          method: 'post',
          timeout: 1000,
          headers: {
            'Accept-Encoding' : 'gzip, deflate',
            'Content-Type':'application/json',
            'Authorization':'Basic YTph'
          },
          data: {
            user: "cheran",
            tokenReceived : token,
    
          },
          auth: {
            username: 'a',
            password: 'a'
          },
        }).then(function(response){
          //console.log(response);
        });
    
    
      }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 2019-08-24
      • 1970-01-01
      • 2022-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      相关资源
      最近更新 更多