2017-03-10 74 views
0

我的通知只适用于一个时间项目。我需要显示我的通知:下午10点和晚上10点30分。我该怎么做?请告诉我重复通知Swift 3

我的代码:

NotificationManager.swift:

import UIKit 
import UserNotifications 

class NotificationManager 
{ 
static let shared = NotificationManager() 
let center = UNUserNotificationCenter.current() 

func registerNotifications() 
{ 
    center.requestAuthorization(options: [.sound,.alert], completionHandler: {(granted, error) in }) 
} 

func addNotificationWithCalendarTrigger(hour: Int, minute: Int) 
{ 
    let content = UNMutableNotificationContent() 
    content.title = "Hi" 
    content.body = "It,s new notification!" 
    content.sound = UNNotificationSound.default() 

    var components = DateComponents() 

    components.hour = hour 
    components.minute = minute 

    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true) 
    let request = UNNotificationRequest(identifier: "calendar", content: content, trigger: trigger) 

    center.add(request) { (error) in 
     //handle error 
    } 
} 
} 

ViewController.swift

import UIKit 

class ViewController: UIViewController 
{ 
override func viewDidLoad() 
{ 
    super.viewDidLoad() 
    timeForNotifications() 
} 

override func didReceiveMemoryWarning() 
{ 
    super.didReceiveMemoryWarning() 
} 

func timeForNotifications() 
{   
    NotificationManager.shared.addNotificationWithCalendarTrigger(hour: 22, minute: 00) 
} 

} 
+0

您从未设置过代理 center.delegate = self 也不要忘记为类设置UNUserNotificationCenterDelegate – t1ser

回答

0

可能有点晚,但我认为这是你在找什么对于。您可以设置通知在10:00与下面的代码显示:

var components = DateComponents() 

components.hour = 22 
components.minute = 00 

let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true) 
let request = UNNotificationRequest(identifier: "calendar", content: content, trigger: trigger) 

我一直做的是更换日期组件,但我觉得你的选择的作品,以及。

var date = DateComponents() 
date.hour = 22 
date.minute = 00 
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true) 

希望这对你有所帮助!