我正在尝试弄清楚如何在没有用户输入的情况下每天在特定时间(例如上午 8 点)发送一次通知,并使用新UNMutableNotificationContent
而不是已弃用的UILocalNotification
,而不是使用用户输入来触发它,而是使用时间。如果找到的所有解释都是旧的,不包括ios 10和swift 3。
到目前为止,我所拥有的。
ViewController.swift中的授权通知:
override func viewDidLoad() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
})
}
通知.swift
let localNotification = UNMutableNotificationContent()
// localNotification.fireDate = dateFire
localNotification.title = "title"
localNotification.body = "body"
localNotification.badge = 1
localNotification.sound = UNNotificationSound.default()
我知道我必须设置触发器和请求等,但我不确定如何让它工作。
你能看看这个教程吗 - 使用快速通知中心进行黑客攻击
您需要的是日期组件部分。
func scheduleLocal() {
let center = UNUserNotificationCenter.current()
let localNotification = UNMutableNotificationContent()
localNotification.title = "title"
localNotification.body = "body"
localNotification.badge = 1
localNotification.sound = UNNotificationSound.default()
var dateComponents = DateComponents()
dateComponents.hour = 10
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: localNotification, trigger: trigger)
center.add(request)
}
查看教程了解更多信息。它是用swift 3 iOS 10编写的。这是相同的github存储库。
第一步:
import UserNotifications
并判断用户是否允许通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
granted, error in
if granted {
// determine whether the user allows notification
}
}
第二步:
创建通知
// 1. create notification's content
let content = UNMutableNotificationContent()
content.title = "Time Interval Notification"
content.body = "My first notification"
// 2. create trigger
//custom your time in here
var components = DateComponents.init()
components.hour = 8
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
// 3. send request identifier
let requestIdentifier = "com.xxx.usernotification.myFirstNotification"
// 4. create send request
let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
// add request to send center
UNUserNotificationCenter.current().add(request) { error in
if error == nil {
print("Time Interval Notification scheduled: (requestIdentifier)")
}
}
您可以在 Apple 文档中找到更多信息