ios - 特定日期和时间的本地通知不起作用。迅速
问题描述
我试图在按钮单击的特定日期和时间触发本地通知,但它不起作用。下面是代码:
@IBAction func setReminderBtnPressed (_ sender: UIButton) {
var dateString = String()
dateString = "2018-10-20 18:11:00"
//let date = Date(timeIntervalSinceNow: 60) //Working Fine
let date = globalMethods.convertStringToDate(dateStr: dateString) //log 2018-10-20 10:11:00 +0000
let content = UNMutableNotificationContent()
content.title = "Don't forget"
content.body = "Buy some milk"
content.sound = UNNotificationSound.default()
let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) //log ▿ year: 2018 month: 10 day: 20 hour: 18 minute: 11 second: 0 isLeapMonth: false
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print(error)
}
})
}
func convertStringToDate(dateStr: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone.current// (abbreviation: "GMT+0:00")
let dateFromString = dateFormatter.date(from: dateStr)
print("dateFromString: ", dateFromString!)
return dateFromString!
}
提前致谢。
解决方案
确保您已授权该应用向用户发送通知。
在您的AppDelegate中application(_:didFinishLaunchingWithOptions:)
,请求授权:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
if let error = error {
debugPrint("Error: \(error)")
}
}
UNUserNotificationCenter.current().delegate = self
并且,UNUserNotificationCenterDelegate
在您的AppDelegate中确认,并实现该方法:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
推荐阅读
- json - Flutter 在 json 数据中获取和循环
- javascript - 需要在 Firebase 的集合中写入集合
- module - 是否有可以在 Google Colaboratory 中使用的“simplegui”替代模块?
- python - Django:使用复合键的替代方法
- cassandra - Stargate REST API 是否支持 LIMIT 子句?
- typescript - TypeScript:检查对象属性是否为自定义类型
- reactjs - 如何防止我的图表重新渲染?(反应JS)
- apache-spark - 如何使用 Databricks 在 Apache Spark 中使用 SparkSQL 或 PySpark 查询 JSON 中的数组
- php - 是什么导致 Symfony 调用服务?
- python - 如何在python中以更好的方式将ECLAT算法的水平格式转换为垂直格式?