毎度のことながら自分用の劣化コピー備忘録ブログです。
自分がメインで手を入れているアプリはObjective-Cで作って徐々にSwiftに置き換わっています。
そんな中でlocalNotificationがiOS10以降でdepricatedになりUNUserNotificationCenterを推奨されたので調べてみました。
参考サイト
Xcode|iOS10で新しくなったUNUserNotificationCenterの使い方を調べてみた
ローカルプッシュ通知(iOS10以降) – Qiita
[iOS 10] User Notifications framework を使用してリモート通知を受け取る処理を実装する #wwdc | DevelopersIO
まずUNUserNotificationCenterを使う前提としてUserNotifications.frameworkが必要です。
入れておきましょう。
とりあえず未だ、AppDelegateはObjective-CなんでObjective-Cで書きます。
まずはUserNotificationをインポートしてデリゲートをセットします。
~略~ #import "AppDelegate.h" @import UserNotifications; @interface AppDelegate ()<UIApplicationDelegate,UNUserNotificationCenterDelegate> { ~略~
次にUNUserNotificationCenterのユーザーに対する許諾をもらう部分です。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. //バッジ、サウンド、バナーの許可を求める。 [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert ) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { // APNSはここで設定するの? } }]; [UNUserNotificationCenter currentNotificationCenter].delegate = self; // [application registerForRemoteNotifications];//これはリモート通知の場合に要るのかな?
以上でアプリがバックグランドの時はローカル通知を受けれますが、フォアグラウンドでも通知が受けれるようにするには下記のメソッドを追加します。
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // アプリがフォアグランドにいた場合の通知動作を指定する。 completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert); };
viewControllerはほぼSwiftに置き換わってるのでObjective-Cでのテストはしていません。
以下は参考サイトからのコピペですすみません。
多分動くと思います。(-人-)
// UserNotificationsのインポートが必要 - (IBAction)push:(id)sender { // 通知を作成 UNMutableNotificationContent *unMutableNotice = [UNMutableNotificationContent new]; // title、body、soundを設定 unMutableNotice.title = @"おはようございます"; unMutableNotice.body = @"今日も一日頑張ってください!"; unMutableNotice.sound = [UNNotificationSound defaultSound]; // 通知タイミングを設定(今回は、実装後5秒後に通知を受信します) UNTimeIntervalNotificationTrigger *triger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; // リクエストの作成 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"リクエスト" content:unMutableNotice trigger:triger]; // NUserNotificationCenterにリクエストを投げる [UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:request withCompletionHandler:nil]; }
追記。
swiftで通知の許可を貰う場合。
参考サイト
<Swift>iOS 10 User Notifications Framework実装まとめ – Qiita
UserNotifications.frameworkを入れるのは上記と同じ。
で、インポートします。
import UIKit import UserNotifications //ここ @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate ,UNUserNotificationCenterDelegate { //フォアグラウンドで受け取るにはデリゲートも。
didFinishLaunchingWithOptionsで許可を求めます。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //通知許可のRequest。 let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in if granted { print("Allowed") } else { print("Didn't allowed") } } // フォアグラウンドで受け取るため、UNUserNotificationCenter のデリゲートを設定する UNUserNotificationCenter.current().delegate = self return true }
フォアグラウンドでの通知の受け取りは以下のMethodを実装。
// アプリがフォアグラウンドの時に通知を受け取る func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { completionHandler([.sound ,.alert]) // 通知バナー表示、通知音の再生を指定 }
テスト用に5秒で鳴る通知。
//ローカル通知の設定 let content = UNMutableNotificationContent() content.title = "Title" content.subtitle = "Subtitle" // 新登場! content.body = "Body" content.sound = UNNotificationSound.default // 5秒後に発火 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger) // ローカル通知予約 UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
上記をviewWillApperあたりに入れると、開くたびに5秒後に鳴るテストが出来ます。\(^o^)/