每日通报Swift 3

我试图找出如何发送一个通知,每天在特定的时间(比如上午8点),没有用户input,并使用新的UNMutableNotificationContent而不是弃用的UILocalNotification而不是使用用户input来触发它,而是一个时间。 所有的解释如果发现是旧的,不包括ios 10和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() 

我知道我必须设置一个触发器和其他的东西,但我不知道如何得到它的工作。

你可以看看这个教程 – 黑客与迅速通知中心

你需要的是date组件的一部分。

  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 } } 

第二步:

创build通知

 // 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文档中find更多信息