Notification Not Fire on specificTime

时间:2017-08-28 07:33:21

标签: ios swift3

我正在尝试发送本地通知。我的代码如下所述。 问题是该通知没有激发。我尝试了所有可能的回答stackoverflow。请建议。 我清除了所有关于完成启动的通知,并为通知设置了用户权限

func applicationWillTerminate(_ application: UIApplication) {
    self.loadData()
    for obj in eventArray
    {
        if (obj["notification"] as? Bool)!
        {
            scheduleNotification(obj["time"] as! Date, obj["title"] as! String)
            print(obj["time"] as! Date)
        }
    }
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func scheduleNotification(_ date: Date, _ title:String) {
    let formatter = DateFormatter()
    formatter.dateFormat = "HH"
    let myhour = formatter.string(from: date)
    let number = NumberFormatter()
    let mynumberhour = number.number(from: myhour)
    let intHour = mynumberhour?.intValue
    print(intHour!)

    formatter.dateFormat = "mm"
    let myminute = formatter.string(from: date)
    let mynumberMinute = number.number(from: myminute)
    let intMinute = mynumberMinute?.intValue
    print(intMinute!)

    formatter.dateFormat = "MM"
    let mymonth = formatter.string(from: date)
    let mynumberMonth = number.number(from: mymonth)
    let intMonth = mynumberMonth?.intValue
    print(intMonth!)

    formatter.dateFormat = "dd"
    let myday = formatter.string(from: date)
    let mynumberday = number.number(from: myday)
    let intday = mynumberday?.intValue
    print(intday!)
    let calendar = Calendar.current
    //let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: intMonth, day: intday, hour: intHour, minute: intMinute)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
    let content = UNMutableNotificationContent()
    content.title = " Today's Event"
    content.body = "Event Is Generated"
    content.sound = UNNotificationSound.default()
    let request = UNNotificationRequest(identifier: title, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
        print("Uh oh! We had an error: \(error)")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题我解决了。 我在“func applicationDidEnterBackground”中调用了“func scheduleNotification”并正确地通知了。