iOS请求通知、获取通知状态、跳转到设置页面的实现

iOS 使用 UNUserNotificationCenter 类去管理通知相关的活动

请求通知

1
2
3
4
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (result, error) in
self.showAlertDialog(title: "request notification", message: result.description)
}

获取通知状态

1
2
3
4
5
6
7
8
9
10
11
12
13
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
switch (settings.authorizationStatus) {
case .authorized:
self.showAlertDialog(title: "notification state", message: "authorized")
case .denied:
self.showAlertDialog(title: "notification state", message: "denied")
case .notDetermined:
self.showAlertDialog(title: "notification state", message: "not determined")
default:
self.showAlertDialog(title: "notification state", message: "unknown")
}
}

跳转到设置页面

1
2
3
4
5
let application = UIApplication.shared
let url = URL.init(string: UIApplication.openSettingsURLString)!
if (application.canOpenURL(url)) {
application.open(url, options: [:], completionHandler: nil)
}