前言:App中的新消息通知一般都长这个样子的
里面涉及到了几个点,在这里记录一下
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
let center = UNUserNotificationCenter.current()
override func viewDidLoad() {
super.viewDidLoad()
center.delegate = self
center.getNotificationSettings { (notificationSettings) in
DispatchQueue.main.async {
switch notificationSettings.authorizationStatus {
case .notDetermined://用户尚未决定应用程序是否可以发布用户通知。
self.openAuthorization()
case .denied://应用程序没有被授权发布用户通知。
print("未开启")
case .authorized://应用程序被授权发布用户通知。
print("已开启")
case .provisional://应用程序被授权发布非中断用户通知。
break
default:
break
}
}
}
}
}
代码:
//用户尚未授权
func openAuthorization() {
self.center.requestAuthorization(options: [.badge, .sound, .alert, .carPlay ]) { (flag, error) in
DispatchQueue.main.async {
if flag == true {
print("已开启")
}else{
print("未开启")
}
}
}
}
//打开设置
func openSystemSettings() {
let urlObj = URL(string: UIApplication.openSettingsURLString)
// 前往设置
UIApplication.shared.open(urlObj! as URL, options: [ : ]) { (flag) in
if flag == true {
/// 回调 "已开启"
}else{
/// 回调 "未开启"
}
}
}
func playSystemSound() {
/// 震动开启
if UserDefaults.standard.object(forKey: "SystemVibrate") as? Bool != false {
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
}
/// 声音开启
if UserDefaults.standard.object(forKey: "SystemSound") as? Bool != false {
var soundID:SystemSoundID = 0;
let path = "/System/Library/Audio/UISounds/sms-received1.caf"
let filePath = NSURL.fileURL(withPath: path, isDirectory: false)
AudioServicesCreateSystemSoundID(filePath as CFURL, &soundID)
AudioServicesPlaySystemSound(soundID)
}
}