我已經設置了一個本地通知系統,以便我可以每天在特定時間發出通知。這一次是由用戶決定的,我把它存儲爲一個字符串。我將分解我在代碼中完成的所有步驟,但基本上,我的問題是通知不會觸發。基於日曆的本地通知不能正常工作 - 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」參數。此變量具有我的日期的字符串值。然後我將它轉換爲日期值。通過使用斷點和打印語句,我看到我的所有值包括日期,小時,分鐘等都不是零。
總的來說,我的問題是通知永遠不會發送。不過,我知道這是因爲我用斷點來證明這一點。任何幫助,將不勝感激!
添加通知後,你應該叫'UNUserNotificationCenter.current()getPendingRequests'並檢查您的通知實際上已經隨着檢查下加入。通知的fireoate。 –
它已被添加。添加後,它顯示正確的請求信息並顯示正確的小時和分鐘值。問題是我在模擬器上運行它? –
我已經在模擬器上運行了很多測試,並且它們能夠工作,儘管間歇性地不起作用。要清楚,「設置」應用中的通知設置是什麼? – AlexK