如何在iOS中僅發布一次UILocalNotifivcation

[英]How to Post a UILocalNotifivcation only once in iOS


Im posting a notification in iOS, I dont want to repeat the notification code i have used is.

我在iOS上發布通知,我不想重復我用過的通知代碼。

let notification = UILocalNotification()
notification.timeZone = NSTimeZone.local
//calculation of dateTime
notification.fireDate = dateTime as Date?


notification.repeatInterval = 0

notification.alertBody = "Body"
notification.userInfo = ["title": "Notify", "type": "title", "5436" : "Notify"]

In that condition my notification was not firing. When I give like

在那種情況下,我的通知沒有解雇。當我給予喜歡

notification.repeatInterval = NSCalendar.Unit.day

It is firing.. Is this a feature or issue? How can i post a notification without repeat interval

它正在解雇..這是一個功能還是問題?如何在沒有重復間隔的情況下發布通知

1 个解决方案

#1


2  

Soultion 1: You can use dispatch_once:

Soultion 1:你可以使用dispatch_once:

static var token: dispatch_once_t = 0

dispatch_once(&token) {
  NSLog("Do it once")
}

Solution 2:

解決方案2:

Taken from Apple documentation:

取自Apple文檔:

If you assign an calendar unit such as weekly (NSWeekCalendarUnit) or yearly (NSYearCalendarUnit), the system reschedules the notification for delivery at the specified interval. The default value is 0, which means don't repeat.

如果您指定日歷單位(例如每周(NSWeekCalendarUnit)或每年(NSYearCalendarUnit)),系統將按指定的時間間隔重新安排通知以進行交付。默認值為0,表示不重復。

I assume you want to cancel the notification with the repeating interval, you can do that in two ways:

我假設您想要以重復間隔取消通知,您可以通過兩種方式執行此操作:

Cancel all the notifications.

取消所有通知。

Cancel only that notification.

僅取消該通知。

The first option is easy, use:

第一個選項很簡單,使用:

cancelAllLocalNotifications In your app delegate.

cancelAllLocalNotifications在您的app delegate中。

The second one requires more work. You need to go through the pending notifications (use scheduledLocalNotifications) and cancel the notification.

第二個需要更多的工作。您需要瀏覽待處理的通知(使用scheduledLocalNotifications)並取消通知。

In order to know which notifications is going to be canceled you can use the userInfo property when you set the notification. For example set an unique ID for every notification so when you cancel that notification you simply compare that ID with all the IDs in your scheduledLocalNotifications array.

為了知道要取消哪些通知,您可以在設置通知時使用userInfo屬性。例如,為每個通知設置唯一ID,因此當您取消該通知時,只需將該ID與scheduledLocalNotifications數組中的所有ID進行比較即可。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/06/07/725efbaab8cc8db4a91100ea463095fa.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com