🟧
Swiftでローカルでのプッシュ通知をやってみる
完成画面 |
---|
![]() |
UserNotificationsを使用する
以下の手順で追加
-
Xcodeのプロジェクトナビゲーターで、プロジェクトファイルを選択
-
"Target"セクションで"Build Phases"タブを開く
-
"Link Binary With Libraries"セクションで"+"ボタンをクリックしてUserNotifications.frameworkとUserNotificationsUI.frameworkを追加(画像のように検索すると良い)
通知の許可を行う場合は、AppDelegate.swiftに以下を追加する
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// いかを追記
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
// 通知の許可が得られた場合の処理
UNUserNotificationCenter.current().delegate = self
} else {
// 通知の許可が得られなかった場合の処理
print("Notification permission denied")
}
}
return true
}
フォアグラウンドで通知したい場合は以下を実装
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if #available(iOS 14.0, *) {
completionHandler([[.banner, .list, .sound]])
} else {
completionHandler([[.alert, .sound]])
}
}
}
通知処理
今回はボタン押下から5秒後にプッシュ通知するように実装
UNNotificationRequestの引数のtriggerにnilを設定することで即時通知可能
class ViewController: UIViewController {
@IBOutlet weak var pushNotificationButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func onClickPushNotificationButton(_ sender: Any) {
// 通知の内容を作成
let content = UNMutableNotificationContent()
content.title = "タイトル"
content.body = "メッセージ"
// 通知のトリガーを作成
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// 通知リクエストを作成
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// 通知をスケジュール
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
// 通知のスケジュールに失敗した場合の処理
print("Failed to schedule notification error: \(error)")
} else {
// 通知のスケジュールに成功した場合の処理
print("Successfully scheduled notification")
}
}
}
}
Discussion