在我的应用程序中,我应用了一个代码,每次用户转到特定的视图控制器时,都会停止发送通知,但现在下载后,通知一开始只发送一次。如何在应用程序刷新后将其更改为每次只显示一次通知?这是代码:
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])
}
}
当您将某些内容存储到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
}
或者,如果你有一种在整个应用程序中共享状态的方法(也许是singleton(,你可以避免UserDefaults,并将其保存为你使用的任何类的成员。