2017-08-03 9 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") 
     } 
    } 
} 

//これからのget許可のためであります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 
    } 

と私はノー通知を受信して​​いる私のアプリを閉じたとき、あなたはあなたの通知を追加した後center.removeAllPendingNotificationRequests()を呼び出すべきではありません、私は特定の時間にローカル通知をトリガーする方法について

おかげ

答えて

1

を助けてください以前に追加された保留中の通知もキャンセルされるためです。あなたはむしろあなたの要求が実際に

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

それとも、また、要求が正常に追加されていない場合は、エラーが返される、addRequestに完了ハンドラを指定することができますによって追加されているか否かをcenter.addRequest(request)を呼び出した後にチェックする必要があります:

center.add(request, withCompletionHandler: { error in 
    print(error) 
}) 
関連する問題