背景
iOS10での通知周りの記事は多くあったが、古い記事になってしまったので、改めて実装を試してみた。
実装はStoryboardで行っています。
必要な手順
①通知の許可リクエスト
②SceneDelegateを使わない設定を行う
③適当に通知を飛ばす
④Storyboardで2画面目を追加してUserNitificationCenterのdelegateで遷移処理を実装
通知の許可リクエスト
AppDelegate.swift
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
return true
}
// 省略
}
SceneDelegateを使わない設定を行う
こちらの記事を参考に使わない設定を行います。
https://qiita.com/u5_03/items/ff005e7cab7ff509f140
適当に通知を飛ばす
ViewController.swift
class ViewController: UIViewController,CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
let content = UNMutableNotificationContent()
content.title = "Hello!"
content.body = "World!"
content.sound = UNNotificationSound.default
// 5秒後に発火する UNTimeIntervalNotificationTrigger 作成、
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
// identifier, content, trigger から UNNotificationRequest 作成
let request = UNNotificationRequest.init(identifier: "FiveSecondNotification", content: content, trigger: trigger)
// UNUserNotificationCenter に request を追加
let center = UNUserNotificationCenter.current()
center.add(request)
}
}
Storyboardで2画面目を追加してUserNitificationCenterのdelegateで遷移処理を実装
画面追加と遷移の処理ははこちらを参考にしてください!
https://qiita.com/tomu28/items/4bb327a8f80c042e41a1
AppDelegate.swift
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let center = UNUserNotificationCenter.current()
// delegateを設定
center.delegate = self
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
return true
}
// 通知をタップするとこのメソッドが呼ばれる
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
self.window = UIWindow(frame: UIScreen.main.bounds)
// Storyboardを指定
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// Viewcontrollerを指定
let initialViewController = storyboard.instantiateViewController(withIdentifier:"second")
// rootViewControllerに入れる
self.window?.rootViewController = initialViewController
// 表示
self.window?.makeKeyAndVisible()
}
}
上記で通知タップ時に指定画面に遷移することが可能です、