Swift 6での書き方
Swift 6ではUILocalNotificationではなくUserNotificationsを使うよ。async関数からtry await scheduleReminder()と呼び、false(許可なし)やエラーを処理してね。許可後、約5秒先の通知を予約する例だよ。同じidentifierの予約は置き換わる。アプリが前面のときも表示したい場合は、UNUserNotificationCenterDelegateの前面表示処理も必要だよ。Apple公式:ローカル通知
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import UserNotifications func makeReminderRequest() -> UNNotificationRequest { let content = UNMutableNotificationContent() content.body = "通知のメッセージだよ" content.sound = .default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) return UNNotificationRequest(identifier: "example-reminder", content: content, trigger: trigger) } func scheduleReminder() async throws -> Bool { let center = UNUserNotificationCenter.current() guard try await center.requestAuthorization(options: [.alert, .sound]) else { return false } try await center.add(makeReminderRequest()) return true } |
以下は旧バージョン当時の記録
サーバとかからのプッシュ通知ではなく、アプリから端末に時間指定で通知を送信する方法。
UILocalNotificationの実装(Swift2.0)
AppDelegate.swift
|
1 2 3 4 5 6 7 8 |
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { //以下を追加 //現在のノーティフケーションを全て削除 UIApplication.sharedApplication().cancelAllLocalNotifications(); //これがないとpermissionエラー application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)) } |
ViewController.swift(通知をキックしたい場所)
|
1 2 3 4 5 6 7 |
let notif = UILocalNotification() notif.fireDate = NSDate(timeIntervalSinceNow: 5) //5秒後 notif.timeZone = NSTimeZone.defaultTimeZone() notif.alertBody = "通知のメッセージだよ" notif.alertAction = "OK" notif.soundName = UILocalNotificationDefaultSoundName UIApplication.sharedApplication().scheduleLocalNotification(notif) |
UILocalNotificationの通知スクリーンショット
ローカルだけど、通知も意外と簡単に実装できたね!
タイマーアプリなんかはこれで十分そう。

