zl程序教程

您现在的位置是:首页 >  其他

当前栏目

iOS15 发送本地通知(附带声音)无法播报

2023-04-18 12:49:47 时间

问题

iOS12.1之后利用本地推送实现消息的语音播报,在iOS15 没有声音。

iOS15版本下,配置UNNotificationSound来替换UNNotificationRequest声音,会出现没法播报问题

原因

iOS15本地推送新增了中断级别属性 interruptionLevel,对通知进行了分级 。而且通知的内容不能为空。

解决方案

使用非Passive的中断级别进行本地通知才会有声音,且本地推送一定要有内容,即body不能为空。content.body = @" 不能为空";

   UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; //标题
    content.sound = [UNNotificationSound soundNamed:[NSString stringWithFormat:@"%@.mp3",mp3Name]];

    content.body = @"语音播报";// 本地推送一定要有内容,即body不能为空。

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000
    if (@available(iOS 15.0, *)) {
        content.interruptionLevel = UNNotificationInterruptionLevelTimeSensitive;//会使手机亮屏且会播放声音;可能会在免打扰模式(焦点模式)下展示
        // @"{"aps":{"interruption-level":"time-sensitive"}}";
        // @"{"aps":{"interruption-level":"active"}}";
        content.body = @"语音播报";// 本地推送一定要有内容,即body不能为空。
    }
#endif

    // repeats,是否重复,如果重复的话时间必须大于60s,要不会报错
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01  repeats:NO];
    /* */
    //添加通知的标识符,可以用于移除,更新等搡作
    NSString * identifier = [[NSUUID UUID] UUIDString];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
    [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {

    }];