swift - 迅速。通过按下按钮获得通知访问权限
问题描述
我确定 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())!
它会在一秒钟后添加通知。但是,不要尝试在一秒钟内添加超过一个。您至少需要设置一分钟。否则你的应用会崩溃。
推荐阅读
- visual-studio - 检查 VS 中是否使用了 sass 变量
- python - 从 Odoo V13 的 ir 附件中删除的 css js 文件
- twitter - 在网站上嵌入多条推文(50-60)的最佳策略是什么?
- python - 编辑器如何知道 python 文件的编码?
- javascript - 在 NextJs 如何使用更改事件更改 getServerSideProps
- jquery - 为什么jquery中每个函数后面的值都会变成字符串?
- python - 如何在 Python 中正确测量排序算法的时间和操作
- javascript - 当我在开瓶器内放置表格或 div 元素时,如何单击我的开瓶器并显示我的内容
- blockly - 如何从 Blockly 中的 input_statement 获取语句堆栈?
- php - 在 Eloquent 关系中将接口绑定到实现