簡體   English   中英

快速顯示本地通知,即使應用終止

[英]swift display local notification even the app terminated

你好,我想發送日常提醒之類的通知,即使應用終止也無法在后台運行,我該怎么做,這是我的代碼

func soundNotification(){

    let prayers = ["fajer","dohor","asr","maghreb","isha"]

    let content = UNMutableNotificationContent()
    content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
    content.badge = 1
    content.sound = UNNotificationSound(named: "salah.mp3")
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)

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

}
func soundNotification(){
    let prayers = ["fajer","dohor","asr","maghreb","isha"]
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let content = UNMutableNotificationContent()
    content.title = "\(prayers[indexOfNextPrayer + 1]) azan will be after 5 minutes"
    content.body = " "
    content.badge = 1
    content.sound = UNNotificationSound(named: "salah.mp3")
    let request = UNNotificationRequest(identifier: "azanSoon", content: content, trigger: trigger)
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("error: \(error)")
        }
    }
}

在日期和時間觸發本地通知。

 func scheduleNotification(at date: Date, message:String) {
    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
    let content = UNMutableNotificationContent()
    content.title = "Reminder"
    content.body = message
    content.sound = UNNotificationSound.default()
    let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("error: \(error)")
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM