1. 程式人生 > >iOS 本地推送以及自定義推送聲音

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中是否已經顯示(未顯示, 你需要手動拖到此列表).

這裡寫圖片描述

彈框效果圖:
這裡寫圖片描述