【发布时间】:2019-01-11 00:42:42
【问题描述】:
在我的 react native 应用程序中,我有它,因此用户可以为特定事件设置本地通知(通过点击按钮)。但是,用户可能会在 iOS 设置中关闭/打开通知,当用户这样做并返回应用程序时,状态不会生效。它生效的唯一方式是当用户退出应用程序然后重新进入时。
export default class Bell extends React.Component {
constructor() {
super();
this.state = {
appState: AppState.currentState,
isNotifActive: true,
isBellActive: false,
alertBody:"",
fireDate: "",
LaunchStatus: "",
notificationPermission: ""
};
}
componentDidMount(){
this.setState({
alertBody: this.props.alertBody,
fireDate:this.props.fireDate,
LaunchStatus: this.props.LaunchStatus
})
AppState.addEventListener('change', (state) => {
if (state === 'active') {
Permissions.check('notification').then(response => { // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
this.setState({ notificationPermission: response })
})
if(this.state.notificationPermission == 'authorized') this.setState({isNotifActive:true}) //problem
else if(this.state.notificationPermission != 'authorized') this.setState({isNotifActive:false})
}
if (state === 'background') {
Permissions.check('notification').then(response => { // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
this.setState({ notificationPermission: response })
})
if(this.state.notificationPermission == 'authorized') this.setState({isNotifActive:true}) //problem?
else if(this.state.notificationPermission != 'authorized') this.setState({isNotifActive:false})
}
})
}
render() {
let LaunchStatus = this.state.LaunchStatus
return (
<Ionicons
name={this.state.isBellActive? "md-notifications":"md-notifications-off"}
color={"white"}
size={30}
style={styles.NotifIcon}
onPress={() => {
Vibration.vibrate()
if(this.state.isNotifActive == true){
if(LaunchStatus == 2){
Alert.alert(
'No Notification Made',
'No launch time is available at the moment, you may toggle a notification when a launch time is made.',
[
{text: 'OK'},
]
);
}
else{
if(this.state.isBellActive){
PushNotificationIOS.scheduleLocalNotification({
alertTitle: "Launching Soon:",
alertBody: this.state.alertBody,
fireDate: this.state.fireDate // in 30 mins
});
this.setState({NotifIcon : "md-notifications"});
this.setState({isBellActive : false});
}
else if(this.state.isBellActive != true){
PushNotificationIOS.cancelLocalNotifications();
this.setState({NotifIcon : "md-notifications-off"});
this.setState({isBellActive : true});
}
}
}
else if(this.state.isNotifActive == false){
PushNotificationIOS.cancelAllLocalNotifications();
this.setState({NotifIcon : "md-notifications-off"});
}
}}
/>
);
}
}
上面的代码所做的是检查应用程序是处于活动状态还是在后台,然后检查 iOS 上的通知权限状态。如果未切换通知,则用户不应在应用程序中切换通知,反之亦然。它可以工作,但是只有在用户关闭/打开通知后 -> 进入应用程序 -> 退出应用程序 -> 然后返回应用程序
【问题讨论】:
标签: reactjs react-native push-notification notifications