2017-06-19 103 views
0

我正在編寫一個應用程序並希望包含本地通知。我希望通知能夠在特定時間和每天重複發送。本地通知提供多次而不僅僅是一個

我把它編入我的應用程序,它確實通知用戶。然而,應用程序並不是每天在設定的時間通知一次,而是在設定的時間向用戶發送13+個通知。通知的數量每天都在增加。

如何解決此問題?我只想讓通知每天通知用戶一次。

這是我的代碼,我一直在使用。它是在應用程序委託的選項完​​成啓動時設置的。

let notificationSettings = UIUserNotificationSettings(forTypes: [.Badge, .Alert, .Sound], categories: nil) 
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) 

let title: String = "Read Today's Pulse Habit!" 

let calendar = NSCalendar.currentCalendar() 
let calendarComponents = NSDateComponents() 
calendarComponents.hour = 15 
calendarComponents.minute = 30 
calendarComponents.second = 0 
calendar.timeZone = NSTimeZone.defaultTimeZone() 
let dateToFire = calendar.dateFromComponents(calendarComponents) 

let notification = UILocalNotification() 

notification.alertBody = "\(title)" 
notification.alertAction = "Read Now" 
notification.fireDate = dateToFire 
notification.alertTitle = "PULSE" 
notification.repeatInterval = NSCalendarUnit.Day 
notification.soundName = UILocalNotificationDefaultSoundName 
notification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1 

UIApplication.sharedApplication().scheduleLocalNotification(notification) 

我甚至嘗試拿出包含遞增圖標徽章號碼的行,並沒有任何區別。

+0

你把這個實現放在哪裏?應用程序委託沒有關聯視圖,因此沒有viewDidLoad方法。 –

+0

糟糕。我的意思是在應用程序委託中完成了與選項的完成啓動。 – Lindsay

回答

2

我猜你是每次啓動你的應用程序時安排一個新的通知。您應該在應用程序中實施自己的邏輯,以取消和/或阻止通知調度,以滿足某些條件。

你讀過關於調度和處理本地通知的official docs嗎?

編輯

找到了一種方法,爲您打印您的當前所有計劃通知到控制檯(SWIFT 3):

let center = UNUserNotificationCenter.current() 

center.getPendingNotificationRequests { (notifications) in 
    print("Count: \(notifications.count)") 
    for item in notifications { 
     print(item.content) 
    } 
} 

繼續前進,將其粘貼到您的didFinishLaunching方法,看看是什麼你得到的結果。

+0

這是否會阻止通知每天發送超過1次? – Lindsay

+0

@Lindsay不,這隻會幫助您調試/檢查您的應用當前計劃的本地通知數量。防止多個計劃通知的一種方法是在通知中添加一個ID,然後在您的應用下次安排通知時檢查此ID。如果它已經存在,請不要安排一個新的。 –

+0

哦,好吧。非常感謝你。我是Xcode和swift編程的新手。我將如何爲通知創建一個ID並檢查它? – Lindsay

相關問題