Swift。通过按下按钮获得通知访问权限
Swift. Gaining notification access by pushing a button
我确定 func 中的代码是正确的,因为它适用于启动应用程序,但不适用于我需要的按钮..
我试过把通知放在按钮里面,但是没用
class SecondViewController: UIViewController {
/*
override func viewDidLoad() {
super.viewDidLoad()
}*/
@IBAction func SubscribeButtonTapped(_ sender: Any) {
// Step 1: Ask for permission
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
}
// Step 2: Create the notification content
let content = UNMutableNotificationContent()
content.title = "Take your ass off"
content.body = "Do something!"
content.sound = UNNotificationSound.default
//Step 3: Create the notification trigger
let date = Date().addingTimeInterval(10)
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: false)
//Step 4: Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest.init(identifier: uuidString, content: content, trigger: trigger)
//Step 5: Register the request
center.add(request) { (error) in
//Check the error paramater and handle any errors
}
}
如果你写let date = Calendar.current.date(byAdding: .second, value: 1, to: Date())!
,它会在一秒钟后添加通知。但是,不要尝试在一秒钟内添加多个。您至少需要设置一分钟。否则您的应用程序将崩溃。
我确定 func 中的代码是正确的,因为它适用于启动应用程序,但不适用于我需要的按钮..
我试过把通知放在按钮里面,但是没用
class SecondViewController: UIViewController {
/*
override func viewDidLoad() {
super.viewDidLoad()
}*/
@IBAction func SubscribeButtonTapped(_ sender: Any) {
// Step 1: Ask for permission
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
}
// Step 2: Create the notification content
let content = UNMutableNotificationContent()
content.title = "Take your ass off"
content.body = "Do something!"
content.sound = UNNotificationSound.default
//Step 3: Create the notification trigger
let date = Date().addingTimeInterval(10)
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: false)
//Step 4: Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest.init(identifier: uuidString, content: content, trigger: trigger)
//Step 5: Register the request
center.add(request) { (error) in
//Check the error paramater and handle any errors
}
}
如果你写let date = Calendar.current.date(byAdding: .second, value: 1, to: Date())!
,它会在一秒钟后添加通知。但是,不要尝试在一秒钟内添加多个。您至少需要设置一分钟。否则您的应用程序将崩溃。