[英]iOS Swift Local notification not "popping up"
我正在嘗試在預定時間發送本地通知。 但是通知沒有出現在屏幕上,但是當我向下滑動時它顯示在通知中心。
這就是我想要達到的目標 這就是我得到的。
此代碼來自我的 AppDelegate 的 didFinishLaunchingWithOptions()。
// Setup local push notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil))
scheduleNotifications()
這是 scheduleNotifications() 的代碼
func scheduleNotifications() {
// create a corresponding local notification
let notification = UILocalNotification()
// Get today's date, time and year
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: NSDate())
// Sets the fire time to 2pm/1400 hours to anticipate user for lunch time
components.hour = 19
components.minute = 13
components.second = 00
notification.fireDate = components.date // Sets the fire date
notification.alertBody = "Enjoyed your lunch? Don't forget to track your expenses!"
notification.alertAction = "Add expense"
notification.repeatInterval = NSCalendarUnit.Day // Repeats the notifications daily
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
任何幫助,將不勝感激。 謝謝!
您的問題是將 NSDateComponents 對象轉換為 NSDate 的方式。
簡單地調用components.date
而不為NSDateComponents
對象設置calendar
將返回nil
。
嘗試改用這個:
notification.fireDate = calendar.dateFromComponents(components)
或者,您可以在組件對象上設置calendar
屬性:
components.calendar = calendar
因為您將通知對象的fireDate
屬性設置為nil
,所以它會立即觸發,即在您有機會關閉應用程序並鎖定屏幕之前。 此行為記錄在UILocalNotification 類參考中
我得到同樣的奇怪行為。 剛剛創建了一個新項目來測試您的代碼。
當您將 fireDate 更改為:
notification.fireDate = NSDate(timeIntervalSinceNow: 10)
你會得到你想要的行為。
希望能有所幫助!
對我來說,當手機通過電纜連接時,通知僅顯示在通知中心 - 當應用程序處於前台時不顯示橫幅。 當電纜斷開連接時,橫幅會顯示在應用程序上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.