在我的應用程式中,我應用了一個代碼,該代碼在每次用戶轉到特定視圖控制器時停止發送通知,但現在通知在下載后一開始只發送一次。如何將其更改為每次重繪 應用程式后僅顯示一次通知?這是代碼:
import UIKit
import UserNotifications
class firstViewController: UIViewController, UNUserNotificationCenterDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.badge,.sound,.alert]) { granted, error in
if error == nil {
print("User permission is granted : \(granted)")
}
}
let defaults = UserDefaults.standard
// Check for flag, will be false if it has not been set before
let userHasBeenNotified = defaults.bool(forKey: "userHasBeenNotified")
// Check if the flag is already true, if it's not then proceed
guard userHasBeenNotified == false else {
// Flag was true, return from function
return
}
// Step-2 Create the notification content
let content = UNMutableNotificationContent()
content.title = "Hello"
content.body = "Welcome"
// Step-3 Create the notification trigger
let date = Date().addingTimeInterval(2)
let dateComponent = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: false)
// Step-4 Create a request
let uuid = UUID().uuidString
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)
// Step-5 Register with Notification Center
center.add(request) { error in
defaults.setValue(true, forKey: "userHasBeenNotified")
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound,.banner,.badge])
}
}
uj5u.com熱心網友回復:
當您將某些內容存盤到 UserDefaults 時,即使在應用程式關閉后它仍然存在。這就是通知不再顯示的原因。
如果您不希望它在應用程式啟動時持續存在,則應false在應用程式啟動時將其設定為(我認為這就是您所說的重繪 的意思):
您可以將其添加到您的UIApplicationDelegate(或將行添加到現有的 didFinishLaunchingWithOptions):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// this clears the flag
UserDefaults.standard.setValue(false, forKey: "userHasBeenNotified")
return true
}
或者,如果您有一種在整個應用程式中共享狀態的方法(可能是單例),您可以避免使用 UserDefaults 并將其保存為您使用的任何類的成員。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/448396.html
