2017-08-03 94 views
0

請問我有關於如何在特定時間觸發本地通知的問題?無需用戶觸發,並需要在特定的時間應用解僱本地通知在特定時間發起本地通知

下面我的代碼:

這是從用戶那裏得到許可

func registerLocal() { 

    let center = UNUserNotificationCenter.current() 

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in 
     if granted { 
      print("Yay!") 
     } else { 
      print("D'oh") 
     } 
    } 
} 

//這個我安排本地通知 FUNC scheduleLocal(){

let center = UNUserNotificationCenter.current() 
    let content = UNMutableNotificationContent() 
    content.title = "Late wake up call" 
    content.body = "The early bird catches the worm, but the second mouse gets the cheese." 
    content.categoryIdentifier = "alarm" 
    content.userInfo = ["customData": "fizzbuzz"] 
    content.sound = UNNotificationSound.default() 



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

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

//她我打電話論文方法

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 

      registerLocal() 
      scheduleLocal() 
     return true 
    } 

,當我關閉我的應用我沒有收到通知,請幫助我如何能夠觸發在特定時間本地通知

感謝

回答

1

加入您的通知後,您不應該調用center.removeAllPendingNotificationRequests() ,因爲它也會取消先前添加的待處理通知。你還是該檢查由

center.getPendingNotificationRequests(completionHandler: { pendingRequest in 
    print("Pending notifications: \(pendingRequest)") //Just for debugging 
}) 

調用center.addRequest(request)是否你的要求實際上已經加入或不經過或者你也可以指定一個完成處理程序addRequest,如果請求沒有被成功地加入它會返回一個錯誤:

center.add(request, withCompletionHandler: { error in 
    print(error) 
})