2017-07-28 39 views
0

我已经设置了一个本地通知系统,以便我可以每天在特定时间发出通知。这一次是由用户决定的,我把它存储为一个字符串。我将分解我在代码中完成的所有步骤,但基本上,我的问题是通知不会触发。基于日历的本地通知不能正常工作 - Swift 3

步骤1: 在这个步骤中,设置警报,请求允许发送通知:

let center = UNUserNotificationCenter.current() 
let options: UNAuthorizationOptions = [.alert, .badge, .sound] 
center.requestAuthorization(options: options) { (granted, error) in 
    if granted { 
     application.registerForRemoteNotifications() 
    } 
} 

第2步: 在这一步我安装我调用该函数来发送通知:

static func sendNotification(stringDate: String) { 
     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "HH:mm" 

     let content = UNMutableNotificationContent() 
     content.title = "Title" 
     content.body = "Detail" 
     content.badge = 1 

     if let date = dateFormatter.date(from: stringDate) { 
      let calendar = Calendar.current 

      let hour = calendar.component(.hour, from: date) 
      let minute = calendar.component(.minute, from: date) 

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

      let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) 
      let request = UNNotificationRequest(identifier: "dateDone", content: content, trigger: trigger) 

      UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 
     } 
    } 

步骤3: 然后我把这个功能在我的应用程序委托文件,像这样:

func applicationDidEnterBackground(_ application: UIApplication) { 
    let defaults = UserDefaults.standard 
    if defaults.object(forKey: "currentUser") != nil { 
     if User.current.desiredTimeForNews.characters.contains("A") { 
      let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "AM", with: "") 
      HelperFunctions.sendNotification(stringDate: stringToBeConverted) 

     } else { 
      let stringToBeConverted = User.current.desiredTimeForNews.replacingOccurrences(of: "PM", with: "") 
      HelperFunctions.sendNotification(stringDate: stringToBeConverted) 
     } 
    } 
} 

重要:正如你可以在我的函数中看到我参加“stringDate”参数。此变量具有我的日期的字符串值。然后我将它转换为日期值。通过使用断点和打印语句,我看到我的所有值包括日期,小时,分钟等都不是零。

总的来说,我的问题是通知永远不会发送。不过,我知道这是因为我用断点来证明这一点。任何帮助,将不胜感激!

+0

添加通知后,你应该叫'UNUserNotificationCenter.current()getPendingRequests'并检查您的通知实际上已经随着检查下加入。通知的fireoate。 –

+0

它已被添加。添加后,它显示正确的请求信息并显示正确的小时和分钟值。问题是我在模拟器上运行它? –

+0

我已经在模拟器上运行了很多测试,并且它们能够工作,尽管间歇性地不起作用。要清楚,“设置”应用中的通知设置是什么? – AlexK

回答

0

对我个人而言,我在一台真实的设备上运行它,它工作。虽然它应该在模拟器上工作,但它不适合我。所以我会试着在真正的设备上运行它,然后再看其他任何东西!

0

该代码似乎没问题。应该在设备上和模拟器上工作。我的猜测是,你有一个时区问题或者与calendar.timezonedateformatter.timezone。然后触发时间恰好发生在不同的时间,然后你会期待什么。 下面插入此检查您的设置后,可查看详细信息:

UNUserNotificationCenter.current() 
.getPendingNotificationRequests(completionHandler: { requests in 
    for (index, request) in requests.enumerated() { 
    print("notification: \(index) \(request.identifier) \(request.trigger)") 
    } 
    })