2017-04-24 87 views
0

我正在使用UNTimeIntervalNotificationTrigger通過以下代碼向用戶發送通知。通知在1小時後發送,即可使用。現在,我想讓用戶能夠重置通知的TimeInterval,以便再次運行相同的通知,但TimeInterval僅在用戶按下此按鈕時纔會重置。這意味着repeats: true不是一個選項。再次發送通知

我的代碼:

let tijd = 15 

@IBAction func change(_ sender: Any) { 
    // Notification 
    let content = UNMutableNotificationContent() 
    content.title = "title" 
    content.body = "body" 
    content.badge = 1 
    content.sound = UNNotificationSound.default() 


    // Timer 
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false) 
    let request = UNNotificationRequest(identifier: bezigheid, content: content, trigger: trigger) 

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 
} 

@IBAction func repeat(_ sender: Any) { 
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false) 
    trigger.invalidate() 
} 

我試圖點擊該按鈕時,重複的無效TimeInterval所,但這只是給了我一個錯誤,所以我不認爲這是一段路要走。執行此操作的方式是什麼? :)

+0

你想要做什麼? – KKRocks

+0

@KKRocks我想重置TimeInterval,以便通知在上一次同一時間過後再次運行。我現在有一些設置,但這只是2個按鈕中完全相同的代碼,我不認爲這應該是解決方案..? –

+0

首先你需要刪除AllPendingNotificationRequests,然後再次發佈新的通知。 – KKRocks

回答

0

首先使用下面的代碼刪除舊的通知://刪除通知

UNUserNotificationCenter.current().removePendingNotification‌​Requests(withIdentif‌​iers: [bezigheid])

然後,您可以像設置第一個通知一樣設置下一個通知!

0

這很簡單,感謝@KKRocks我能找到解決方案。我不得不將其刪除並重新添加相同的通知,看到代碼:

let tijd = 15 

@IBAction func change(_ sender: Any) { 
    // Notification 
    let content = UNMutableNotificationContent() 
    content.title = "title" 
    content.body = "body" 
    content.badge = 1 
    content.sound = UNNotificationSound.default() 

    // Timer 
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false) 
    let request = UNNotificationRequest(identifier: bezigheid, content: content, trigger: trigger) 

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 
} 

@IBAction func repeat(_ sender: Any) {  
    // Remove notification 
    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [bezigheid]) 

    // Notification 
    let content = UNMutableNotificationContent() 
    content.title = "title" 
    content.body = "body" 
    content.badge = 1 
    content.sound = UNNotificationSound.default() 

    // Timer 
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false) 
    let request = UNNotificationRequest(identifier: bezigheid, content: content, trigger: trigger) 

    // Add notification 
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 
}