実装
Storyboard
import UIKit
import UserNotifications
final class HomeViewController: UIViewController {
// MARK: - Properties
@IBOutlet private weak var statusLabel: UILabel!
@IBOutlet private weak var statusButton: UIButton!
private let center = UNUserNotificationCenter.current()
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
requestAuthorization()
}
private func requestAuthorization() {
// 通知を表示するための承認がまだない場合は、承認をリクエストする
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
if let error = error {
print("Error requesting authorization: \(error.localizedDescription)")
} else if granted {
// Authorizationが許可された場合
print("Authorization granted")
} else {
// Authorizationが拒否された場合
print("Authorization denied")
}
}
}
@IBAction func checkNotificationAuthorizationStatus(_ sender: Any) {
self.center.getNotificationSettings { settings in
DispatchQueue.main.async {
switch settings.authorizationStatus {
case .authorized:
self.statusLabel.text = "Status: Authorized"
case .denied:
self.statusLabel.text = "Status: Denied"
case .notDetermined:
self.statusLabel.text = "Status: NotDetermined"
case .provisional:
self.statusLabel.text = "Status: Provisional"
case .ephemeral:
self.statusLabel.text = "Status: Ephemeral"
@unknown default:
fatalError("Unknown authorization status")
}
}
}
}
}
この記事は役に立ちましたか?
貴重なフィードバックありがとうございます!