2017-07-11 89 views
0

我需要製作本地通知,每天在19:30提醒用戶。iOS上的每日本地通知

這裏是我做的:

var dateComponents = DateComponents() 
    dateComponents.hour = 19 
    dateComponents.minute = 30 
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)  

    let identifier = "daily.alarm" 
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) 

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in 
     if error != nil { 
     debugPrint("center.add(request, withCompletionHandler: { (error)") 
     } 
    }) 

然而,我發現,該通知是不警惕19:30。相反,它提前15分鐘提醒。而且,它也不能每天報警。我做錯了什麼?以下功能

回答

0

使用安排您的通知:

func registerLocal() { 
    let center = UNUserNotificationCenter.current() 

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in 
     if granted { 
      print("Yas!") 
     } else { 
      print("Ohhh No!!") 
     } 
    } 
} 

func scheduleLocal() { 
    let center = UNUserNotificationCenter.current() 

    let content = UNMutableNotificationContent() 
    content.title = "Drink Milk" 
    content.body = "Two Servings A Day Keeps Bone Problems At Bay." 
    content.categoryIdentifier = "alarm" 
    content.userInfo = ["customData": "whater"] 
    content.sound = UNNotificationSound.default() 

    var dateComponents = DateComponents() 
    dateComponents.hour = 19 
    dateComponents.minute = 30 

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) 

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) 
    center.add(request) 
} 
+0

我已經做了registerLocal()函數,只是我沒有張貼在這裏,因爲它並不是重點。上述代碼在1930年仍然不會觸發警報。 – user6539552

+0

如何進行測試@ user6539552 –

+0

這對我來說很重要@ user6539552 –