我正在尝试弄清楚如何在每天的特定时间(比如上午8点)发送一次通知,而不需要用户输入,并且使用新的UNMutableNotificationContent而不是过时的UILocalNotification,并且不使用用户输入来触发它,而是使用一个时间。所有的解释都是旧的,不包括iOS10和swift 3。
到目前为止我所知道的。
ViewController.swift中的授权通知:
override func viewDidLoad() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
})
}Notification.swift
let localNotification = UNMutableNotificationContent()
// localNotification.fireDate = dateFire
localNotification.title = "title"
localNotification.body = "body"
localNotification.badge = 1
localNotification.sound = UNNotificationSound.default()我知道我必须在其他事情中设置一个触发器和请求,但我不确定如何让它工作。
发布于 2017-01-22 15:25:49
你能看看这个教程吗-- Hacking with swift Notification center
您需要的是日期组件部分。
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. Here's github repo编写的。
发布于 2017-01-22 15:29:02
第一步:
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 Documentation上找到更多信息
https://stackoverflow.com/questions/41787351
复制相似问题