持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情
安装
yarn add @notifee/react-native
cd ios && pod install && cd ..
简单demo
function Screen() {
async function onDisplayNotification() {
// Request permissions (required for iOS)
await notifee.requestPermission()
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
// Display a notification
await notifee.displayNotification({
title: 'Notification Title',
body: 'Main body content of the notification',
android: {
channelId,
smallIcon: 'name-of-a-small-icon', // optional, defaults to 'ic_launcher'.
// pressAction is needed if you want the notification to open the app when pressed
pressAction: {
id: 'default',
},
},
});
}
return (
<View>
<Button title="Display Notification" onPress={() => onDisplayNotification()} />
</View>
);
}
定时器(设定10s之后触发)
import React from 'react';
import {Text, View, TouchableHighlight} from 'react-native';
import notifee, {TriggerType} from '@notifee/react-native';
import {reminderNotification} from '../../utils/notifee/notification';
export const UserScreen = () => {
const onReminder = async () => {
const date = new Date(Date.now());
date.setSeconds(date.getSeconds() + 10); // 10s后触发
await notifee.createTriggerNotification(
{
id: 'new-show',
title: 'Ozark about to begin in 10 minutes',
body: 'Are you ready? Grab the popcorn',
data: {
showId: 'ozark',
},
android: {
channelId,
smallIcon: 'ic_stat_name',
largeIcon:
'https://media.comicbook.com/2020/06/netflix-ozark-final-season-4-1226955.jpeg',
actions: [
{pressAction: {id: 'dismiss'}, title: 'Dismiss'},
{pressAction: {id: 'default'}, title: 'See more'},
],
},
ios: {
categoryId: 'reminder',
attachments: [
{
url: 'https://media.comicbook.com/2020/06/netflix-ozark-final-season-4-1226955.jpeg?auto=webp&width=1280&height=720&crop=1280:720,smart',
},
],
},
},
{
type: TriggerType.TIMESTAMP,
timestamp: date.getTime(),
},
);
};
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>user!</Text>
<View>
<TouchableHighlight underlayColor="#9575CD" onPress={onReminder}>
<Text>Set Reminder</Text>
</TouchableHighlight>
</View>
</View>
);
};
自定义消息声音
IOS环境
准备音乐文件,放进项目的ios文件夹下,然后打开xcode,将音乐文件拖拽进去,在弹框中选择:
具体可以参照:
- HOW TO ADD A CUSTOM PUSH NOTIFICATION SOUND ON IOS AND ANDROID WITH REACT NATIVE FIREBASE AND FCM
- apple developer - UNNotificationSound
代码:
ios: {
sound: '14428.wav', //如果没有设置这个就没有声音,设置默认值“local.wav”就是跟随系统声音,'14428.wav'就是我们的自定义声音
},