ローカル通知を実装する方法を紹介します!
動作環境
対象 | バージョン |
---|---|
iOS | 13.3.1 |
macOS | Catalina 10.15.3 |
Xcode | 11.3.1 |
Swift | 5.1.3 |
実装の方法
ソースコード
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.
// 通知許可の取得
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert, .sound, .badge]){
(granted, _) in
if granted{
UNUserNotificationCenter.current().delegate = self
}
}
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
// アプリ起動時も通知を行う
completionHandler([ .badge, .sound, .alert ])
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
/// ローカル通知ボタンを押下した際の処理
/// - Parameter sender: ローカル通知ボタン
@IBAction func localPush(_ sender: Any) {
let content = UNMutableNotificationContent()
content.title = "お知らせ"
content.body = "ボタンを押しました。"
content.sound = UNNotificationSound.default
// 直ぐに通知を表示
let request = UNNotificationRequest(identifier: "immediately", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}