applicationIconBadgeNumber

本文介绍在iOS8中如何正确设置应用图标上的角标数字,并提供了针对不同iOS版本的兼容性处理代码示例。

IOS8中要想设置applicationIconBadgeNumber,需要用户的授权,在IOS8中,需要加上下面的代码:

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
但是这两句如果是在IOS7的系统中运行的话就会报错,所以需要先判断IOS的版本,完整代码如下:

float version = [[[UIDevice currentDevice] systemVersion] floatValue];

if (version >= 8.0) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
如果是注册消息推送的话,需要这样写:

float version = [[[UIDevice currentDevice] systemVersion] floatValue];

if (version >= 8.0) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
}

/** * Sample React Native App * https://github.com/facebook/react-native * * @flow */ import * as React from 'react'; import {useState, useEffect} from 'react'; import { Alert, StyleSheet, Text, Pressable, ScrollView, View, DeviceEventEmitter, SafeAreaView, } from 'react-native'; import PushNotificationIOS from '@react-native-community/push-notification-ios'; type ButtonProps = {| onPress: () => void | Promise<void>, label: string, |}; const Button: React.StatelessFunctionalComponent<ButtonProps> = ({ onPress, label, }) => { return ( /** $FlowFixMe */ <Pressable style={styles.button} onPress={onPress}> <Text style={styles.buttonLabel}>{label}</Text> </Pressable> ); }; export const App = (): React.Node => { const [permissions, setPermissions] = useState({}); useEffect(() => { PushNotificationIOS.addEventListener('register', onRegistered); PushNotificationIOS.addEventListener( 'registrationError', onRegistrationError, ); PushNotificationIOS.addEventListener('notification', onRemoteNotification); PushNotificationIOS.addEventListener( 'localNotification', onLocalNotification, ); PushNotificationIOS.requestPermissions({ alert: true, badge: true, sound: true, critical: true, }).then( (data) => { console.log('PushNotificationIOS.requestPermissions', data); }, (data) => { console.log('PushNotificationIOS.requestPermissions failed', data); }, ); return () => { PushNotificationIOS.removeEventListener('register'); PushNotificationIOS.removeEventListener('registrationError'); PushNotificationIOS.removeEventListener('notification'); PushNotificationIOS.removeEventListener('localNotification'); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const sendNotification = () => { DeviceEventEmitter.emit('remoteNotificationReceived', { remote: true, aps: { alert: {title: 'title', subtitle: 'subtitle', body: 'body'}, badge: 1, sound: 'default', category: 'REACT_NATIVE', 'content-available': 1, 'mutable-content': 1, }, }); }; const sendSilentNotification = () => { DeviceEventEmitter.emit('remoteNotificationReceived', { remote: true, aps: { category: 'REACT_NATIVE', 'content-available': 1, }, }); }; const sendLocalNotification = () => { PushNotificationIOS.presentLocalNotification({ alertTitle: 'Sample Title', alertBody: 'Sample local notification', applicationIconBadgeNumber: 1, }); }; const sendLocalNotificationWithSound = () => { PushNotificationIOS.addNotificationRequest({ id: 'notificationWithSound', title: 'Sample Title', subtitle: 'Sample Subtitle', body: 'Sample local notification with custom sound', sound: 'customSound.wav', badge: 1, }); }; const scheduleLocalNotification = () => { PushNotificationIOS.scheduleLocalNotification({ alertBody: 'Test Local Notification', fireDate: new Date(new Date().valueOf() + 2000).toISOString(), }); }; const addNotificationRequest = () => { PushNotificationIOS.addNotificationRequest({ id: 'test', title: 'title', subtitle: 'subtitle', body: 'body', category: 'test', threadId: 'thread-id', fireDate: new Date(new Date().valueOf() + 2000), repeats: true, userInfo: { image: 'https://www.github.com/Naturalclar.png', }, }); }; const addCriticalNotificationRequest = () => { PushNotificationIOS.addNotificationRequest({ id: 'critical', title: 'Critical Alert', subtitle: 'subtitle', body: 'This is a critical alert', category: 'test', threadId: 'thread-id', isCritical: true, fireDate: new Date(new Date().valueOf() + 2000), repeats: true, }); }; const addMultipleRequests = () => { PushNotificationIOS.addNotificationRequest({ id: 'test-1', title: 'First', subtitle: 'subtitle', body: 'First Notification out of 3', category: 'test', threadId: 'thread-id', fireDate: new Date(new Date().valueOf() + 10000), repeats: true, }); PushNotificationIOS.addNotificationRequest({ id: 'test-2', title: 'Second', subtitle: 'subtitle', body: 'Second Notification out of 3', category: 'test', threadId: 'thread-id', fireDate: new Date(new Date().valueOf() + 12000), repeats: true, }); PushNotificationIOS.addNotificationRequest({ id: 'test-3', title: 'Third', subtitle: 'subtitle', body: 'Third Notification out of 3', category: 'test', threadId: 'thread-id', fireDate: new Date(new Date().valueOf() + 14000), repeats: true, }); }; const getPendingNotificationRequests = () => { PushNotificationIOS.getPendingNotificationRequests((requests) => { Alert.alert('Push Notification Received', JSON.stringify(requests), [ { text: 'Dismiss', onPress: null, }, ]); }); }; const setNotificationCategories = async () => { PushNotificationIOS.setNotificationCategories([ { id: 'test', actions: [ {id: 'open', title: 'Open', options: {foreground: true}}, { id: 'ignore', title: 'Desruptive', options: {foreground: true, destructive: true}, }, { id: 'text', title: 'Text Input', options: {foreground: true}, textInput: {buttonTitle: 'Send'}, }, ], }, ]); Alert.alert( 'setNotificationCategories', `Set notification category complete`, [ { text: 'Dismiss', onPress: null, }, ], ); }; const removeAllPendingNotificationRequests = () => { PushNotificationIOS.removeAllPendingNotificationRequests(); }; const removePendingNotificationRequests = () => { PushNotificationIOS.removePendingNotificationRequests(['test-1', 'test-2']); }; const onRegistered = (deviceToken) => { Alert.alert('Registered For Remote Push', `Device Token: ${deviceToken}`, [ { text: 'Dismiss', onPress: null, }, ]); }; const onRegistrationError = (error) => { Alert.alert( 'Failed To Register For Remote Push', `Error (${error.code}): ${error.message}`, [ { text: 'Dismiss', onPress: null, }, ], ); }; const onRemoteNotification = (notification) => { const isClicked = notification.getData().userInteraction === 1; const result = ` Title: ${notification.getTitle()};\n Subtitle: ${notification.getSubtitle()};\n Message: ${notification.getMessage()};\n badge: ${notification.getBadgeCount()};\n sound: ${notification.getSound()};\n category: ${notification.getCategory()};\n content-available: ${notification.getContentAvailable()};\n Notification is clicked: ${String(isClicked)}.`; if (notification.getTitle() == undefined) { Alert.alert('Silent push notification Received', result, [ { text: 'Send local push', onPress: sendLocalNotification, }, ]); } else { Alert.alert('Push Notification Received', result, [ { text: 'Dismiss', onPress: null, }, ]); } notification.finish('UIBackgroundFetchResultNoData') }; const onLocalNotification = (notification) => { const isClicked = notification.getData().userInteraction === 1; Alert.alert( 'Local Notification Received', `Alert title: ${notification.getTitle()}, Alert subtitle: ${notification.getSubtitle()}, Alert message: ${notification.getMessage()}, Badge: ${notification.getBadgeCount()}, Sound: ${notification.getSound()}, Thread Id: ${notification.getThreadID()}, Action Id: ${notification.getActionIdentifier()}, User Text: ${notification.getUserText()}, Notification is clicked: ${String(isClicked)}.`, [ { text: 'Dismiss', onPress: null, }, ], ); }; const showPermissions = () => { PushNotificationIOS.checkPermissions((permissions) => { setPermissions({permissions}); }); }; return ( <View style={[styles.flex, styles.background]}> <SafeAreaView style={styles.flex}> <ScrollView contentContainerStyle={styles.container}> <Button onPress={sendNotification} label="Send fake notification" /> <Button onPress={sendLocalNotification} label="Send fake local notification" /> <Button onPress={sendLocalNotificationWithSound} label="Send fake local notification with custom sound" /> <Button onPress={scheduleLocalNotification} label="Schedule fake local notification" /> <Button onPress={addNotificationRequest} label="Add Notification Request" /> <Button onPress={addCriticalNotificationRequest} label="Add Critical Notification Request (only works with Critical Notification entitlement)" /> <Button onPress={addMultipleRequests} label="Add Multiple Notification Requests" /> <Button onPress={setNotificationCategories} label="Set notification categories" /> <Button onPress={removePendingNotificationRequests} label="Remove Partial Pending Notification Requests" /> <Button onPress={removeAllPendingNotificationRequests} label="Remove All Pending Notification Requests" /> <Button onPress={sendSilentNotification} label="Send fake silent notification" /> <Button onPress={() => PushNotificationIOS.setApplicationIconBadgeNumber(42) } label="Set app's icon badge to 42" /> <Button onPress={() => PushNotificationIOS.setApplicationIconBadgeNumber(0)} label="Clear app's icon badge" /> <Button onPress={getPendingNotificationRequests} label="Get Pending Notification Requests" /> <View> <Button onPress={showPermissions} label="Show enabled permissions" /> <Text>{JSON.stringify(permissions)}</Text> </View> </ScrollView> </SafeAreaView> </View> ); }; const styles = StyleSheet.create({ background: { backgroundColor: '#F5FCFF', }, flex: {flex: 1}, container: { flexGrow: 1, backgroundColor: '#F5FCFF', }, button: { padding: 10, alignItems: 'center', justifyContent: 'center', }, buttonLabel: { color: 'blue', }, }); 这个代码在最新的react-native 版本会不会有问题
最新发布
10-26
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值