2017-03-10 103 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) 

希望這對你有所幫助!