我设置了一个本地通知系统,以便我可以在每天的特定时间发出通知。这个时间由用户确定,我将其存储为字符串。我将分解我在代码中完成的所有步骤,但基本上,我的问题是通知不会触发。
第 1 步: 在此步骤中,我设置了一个警报以请求发送通知的权限:
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound]
center.requestAuthorization(options: options) { (granted, error) in
if granted {
application.registerForRemoteNotifications()
}
}
第 2 步: 在此步骤中,我设置了调用来发送通知的函数:
static func sendNotification(stringDate: String) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Detail"
content.badge = 1
if let date = dateFormatter.date(from: stringDate) {
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "dateDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
第 3 步: 然后我在我的应用程序委托(delegate)文件中调用此函数,如下所示:
func applicationDidEnterBackground(_ application: UIApplication) {
let defaults = UserDefaults.standard
if defaults.object(forKey: "currentUser") != nil {
if User.current.desiredTimeForNews.characters.contains("A") {
let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "AM", with: "")
HelperFunctions.sendNotification(stringDate: stringToBeConverted)
} else {
let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "PM", with: "")
HelperFunctions.sendNotification(stringDate: stringToBeConverted)
}
}
}
重要:正如您在我的函数中看到的,我采用了“stringDate”参数。该变量有一个我的日期的字符串值。然后我将其转换为日期值。通过使用断点和打印语句,我发现我的所有值(包括日期、小时、分钟等)都不为零。
总的来说,我的问题是通知从未发送。但是我知道它被调用,因为我已经使用断点来证明这一点。任何帮助将不胜感激!
最佳答案
就我个人而言,我在真实设备上运行了它并且它有效。虽然它应该可以在模拟器上运行,但它不适合我。因此,在查看其他内容之前,我会尝试在真实设备上运行它!
关于ios - 基于日历的本地通知不起作用 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45377592/