阅读 318

iOS自定义通知声音(ios app自定义通知提示音)

场景

在消息推送里面播放自定义生成的声音

解决方案

  1. 生成自定义声音文件后,必须要写入到【/Library/Sounds/】才能进行播放

///往声音目录/Library/Sounds/写入音频文件
- (void)writeMusicDataWithUrl:(NSString*)filePath
                     callback:(void(^)(BOOL success,NSString * fileName))blockCallback{
    NSString *bundlePath = filePath;
    NSString *libPath = [NSHomeDirectory() stringByAppendingString:@"/Library/Sounds/"];

    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:libPath]) {
        NSError *error;
        [manager createDirectoryAtPath:libPath withIntermediateDirectories:YES attributes:nil error:&error];
    }

    NSData *data = [NSData dataWithContentsOfFile:bundlePath];
    
    BOOL flag = [data writeToFile:[libPath stringByAppendingString:[filePath lastPathComponent]] atomically:YES];
    if (flag) {
        NSLog(@"文件写成功");
        if (blockCallback) {
            blockCallback(YES,[filePath lastPathComponent]);
        }
    }else{
        NSLog(@"文件写失败");
        if (blockCallback) {
            blockCallback(NO,nil);
        }
    }
}复制代码
  1. 在【UNMutableNotificationContent】的【sound】参数中写入文件名

///!!!!:推送语音播报
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; //标题
            content.sound = [UNNotificationSound soundNamed:fileName];
            
            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) {
                completed();
            }];


作者:freesan44
链接:https://juejin.cn/post/7029245981149364255


文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐