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