如何在 Swift 的特定时间发送本地通知?
How do I send local notifications at a specific time in Swift?
我一直在寻找关于如何在一天中的特定时间发送通知的答案。我需要它在每个工作日 8:00 A.M 向用户设备显示本地通知。我知道这个问题之前已经回答过。我发现了一个 Stack Overflow 问题:
不幸的是,自 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")
}
}
}
}
Swift 5
这是我使用通知中心安排本地通知的示例。
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//MARK: Authorization
let center = UNUserNotificationCenter.current()
//Delegate for UNUserNotificationCenterDelegate
center.delegate = self
//Permission for request alert, soud and badge
center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// Enable or disable features based on authorization.
if(!granted){
print("not accept authorization")
}else{
print("accept authorization")
center.delegate = self
}
}
return true
}
}
发送通知
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "We have a new message for you", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Open the app for see", arguments: nil)
content.sound = UNNotificationSound.default
content.badge = 1
let identifier = id.uuidString
//Receive notification after 5 sec
//let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
//Receive with date
var dateInfo = DateComponents()
dateInfo.day = day //Put your day
dateInfo.month = month //Put your month
dateInfo.year = year // Put your year
dateInfo.hour = 8 //Put your hour
dateInfo.minute = 0 //Put your minutes
//specify if repeats or no
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
print(identifier)
center.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}else{
print("send!!")
}
}
记得阅读文档中的内容:
我一直在寻找关于如何在一天中的特定时间发送通知的答案。我需要它在每个工作日 8:00 A.M 向用户设备显示本地通知。我知道这个问题之前已经回答过。我发现了一个 Stack Overflow 问题:
不幸的是,自 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")
}
}
}
}
Swift 5
这是我使用通知中心安排本地通知的示例。
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//MARK: Authorization
let center = UNUserNotificationCenter.current()
//Delegate for UNUserNotificationCenterDelegate
center.delegate = self
//Permission for request alert, soud and badge
center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// Enable or disable features based on authorization.
if(!granted){
print("not accept authorization")
}else{
print("accept authorization")
center.delegate = self
}
}
return true
}
}
发送通知
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "We have a new message for you", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Open the app for see", arguments: nil)
content.sound = UNNotificationSound.default
content.badge = 1
let identifier = id.uuidString
//Receive notification after 5 sec
//let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
//Receive with date
var dateInfo = DateComponents()
dateInfo.day = day //Put your day
dateInfo.month = month //Put your month
dateInfo.year = year // Put your year
dateInfo.hour = 8 //Put your hour
dateInfo.minute = 0 //Put your minutes
//specify if repeats or no
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
print(identifier)
center.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}else{
print("send!!")
}
}
记得阅读文档中的内容: