iOS 本地推送以及自定义推送声音

iOS10.0以后苹果要求本地推送使用UserNotification框架来做本地推送, 下文就该框架下做推送以及自定义推送声音做下介绍

1.AppDelegate.m:

1.导入框架并遵循协议:

#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

2.修改或添加以下方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 获取版本号
    CGFloat version = [[UIDevice currentDevice].systemVersion doubleValue];
    // 注册本地推送
    if (version >= 8.0 && version< 10.0) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
        if ([[UIApplication sharedApplication]currentUserNotificationSettings].types==UIUserNotificationTypeNone) {
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
            [application registerUserNotificationSettings:settings];
        }
#endif
    }else if(version >= 10.0){

        // 使用 UNUserNotificationCenter 来管理通知
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //监听回调事件
        center.delegate = self;
        // 获取当前的通知设置,UNNotificationSettings 是只读对象,不能直接修改,只能通过以下方法获取
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"%@", settings);
        }];

        //iOS 10.0以上 使用以下方法注册,才能得到授权
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            // Enable or disable features based on authorization.
            NSLog(@"%d", granted);
        }];
    }

    // 界面的跳转(针对应用程序被杀死的状态下的跳转)
    // 杀死状态下的,界面跳转并不会执行下面的方法- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification,
    // 所以我们在写本地通知的时候,要在这个与下面方法中写,但要判断,是通过哪种类型通知来打开的
    // iOS 10之前
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
    if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) {
        // 跳转代码
        UILabel *redView = [[UILabel alloc] init];
        redView.frame = CGRectMake(0, 0, 200, 300);
        redView.numberOfLines = 0;
        redView.font = [UIFont systemFontOfSize:12.0];
        redView.backgroundColor = [UIColor redColor];
        redView.text = [NSString stringWithFormat:@"%@", launchOptions];
        [self.window.rootViewController.view addSubview:redView];
    }
#endif
    // iOS 10之后直接使用代理方法:- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler


    return YES;

}

//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
/*
 应用程序在进入前台,或者在前台的时候都会执行该方法
 */
// iOS10.0之前[4.0, 10.0]使用下面的方法
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    // 必须要监听--应用程序在后台的时候进行的跳转
    // 应用程序在后台, 用户点击推送的消息后
    if (application.applicationState == UIApplicationStateInactive) {
        NSLog(@"进行界面的跳转");
        // 如果在上面的通知方法中设置了一些,可以在这里打印额外信息的内容,就做到监听,也就可以根据额外信息,做出相应的判断

        UIView *redView = [[UIView alloc] init];
        redView.frame = CGRectMake(0, 0, 100, 100);
        redView.backgroundColor = [UIColor redColor];
        [self.window.rootViewController.view addSubview:redView];
    }
    NSLog(@"%@", notification.userInfo);
}
#endif
#pragma mark - UNUserNotificationCenterDelegate
// iOS10.0之后使用下面的方法(注意:iOS10.0以后, 无论app是否在前台(前台, 后台, 杀掉), 点击推送消息后都会触发这个方法)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{

    UNNotificationContent *content=response.notification.request.content;
    NSLog(@"title: %@, body: %@, sound: %@", content.title, content.body, content.sound);

    UILabel *cyanLabel = [[UILabel alloc] init];
    cyanLabel.frame = CGRectMake(0, 20, 200, 300);
    cyanLabel.text=content.body;
    cyanLabel.backgroundColor = [UIColor cyanColor];
    [self.window.rootViewController.view addSubview:cyanLabel];

    completionHandler();
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

#pragma mark - UNUserNotificationCenterDelegate
//在展示通知前进行处理,即有机会在展示通知前再修改通知内容。
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    //1. 处理通知

    //2. 处理完成后调用 completionHandler ,用于指示在前台显示通知的形式
    completionHandler(UNNotificationPresentationOptionAlert);
}

2.需要触发本地推送的地方(以ViewController.m为例):

1.导入框架:

#import <UserNotifications/UserNotifications.h>

2.定义本地推送方法:

- (IBAction)push:(UIButton *)sender {

    // ios 10之前
    CGFloat version = [[UIDevice currentDevice].systemVersion doubleValue];
    // 注册本地推送
    if (version >= 8.0 && version< 10.0) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0

        // 10.0之前推送设置...
        // ...
    }else if(version >= 10.0){
        // 使用 UNUserNotificationCenter 来管理通知
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

        //需创建一个包含待通知内容的 UNMutableNotificationContent 对象,注意不是 UNNotificationContent ,此对象为不可变对象。
        UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
        content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];
        content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body"
                                                             arguments:nil];
        // 使用定制声音
        content.sound=[UNNotificationSound soundNamed:@"unbelievable.caf"];

        // 默认声音
        // content.sound =[UNNotificationSound defaultSound];

        // 在 alertTime 后推送本地推送
        UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:3.0f repeats:NO];

        UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                              content:content trigger:trigger];

        //添加推送成功后的处理!
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:@"成功添加推送" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:cancelAction];
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
        }];
    }
}

注意:

1.用作自定义声音的音频文件有以下要求:

自定义的弹框铃声是由系统设备播放的, 所以铃声应当是以下数据格式: 
Linear PCM

MA4 (IMA/ADPCM)

µLaw

aLaw
你可以将音频数据打包成一个aiff, wav, 或者caf的文件. 铃声文件的音频长度应少于30秒, 否则将设置无效而播放默认的铃声.


苹果原文:
Custom alert sounds are played by the system sound facility, so they must be in one of the following audio data formats:

Linear PCM

MA4 (IMA/ADPCM)

µLaw

aLaw

You can package the audio data in an aiff, wav, or caf file. Sound files must be less than 30 seconds in length. If the sound file is longer than 30 seconds, the system plays the default sound instead. 

2.将音频文件拖入工程中后, 务必确认下文件在Target–Build Phases–Copy Bundle Resources中是否已经显示(未显示, 你需要手动拖到此列表).

这里写图片描述

弹框效果图:
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值