我一直在寻找有关如何在一天中的特定时间发送通知的答案。我需要它在每个工作日的上午 8:00 向用户的设备显示本地通知。我知道这个问题之前已经回答过。我发现了一个 Stack Overflow 问题:Local Notifications at a specific time
不幸的是,它已经过时了,因为自 iOS 11 发布以来,大部分代码都从 Swift 中删除了。我需要一个更新的答案。我是 Swift 编程的新手。如果有人可以帮助我并给我一个更新的答案,那就太棒了!
最佳答案
这是我使用通知中心安排本地通知的示例。
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "My title"
content.body = "Lots of text"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "yourIdentifier"
content.userInfo = ["example": "information"] // You can retrieve this when displaying notification
// Setup trigger time
var calendar = Calendar.current
calendar.timeZone = TimeZone.current
let testDate = Date() + 5 // Set this to whatever date you need
let trigger = UNCalendarNotificationTrigger(dateMatching: testDate, repeats: false)
// Create request
let uniqueID = UUID().uuidString // Keep a record of this if necessary
let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)
center.add(request) // Add the notification request
Date
对象(由上面的 testDate
表示)可以是您想要的任何日期。从 DateComponents
创建它通常很方便。
您需要在启动时在 App Delegate 中请求本地通知的权限才能使其正常工作。这是一个例子。
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Ask permission for notifications
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Permission granted")
} else {
print("Permission denied\n")
}
}
}
}
关于ios - 如何在 Swift 中的特定时间发送本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009454/