在 swift 中安排本地通知

Scheduling local notifications in swift

在我的应用程序中,我应用了一个代码,该代码在用户每次转到特定视图控制器时停止发送通知,但现在通知仅在下载后的最开始发送一次。如何将其更改为每次刷新应用后仅显示一次通知?这是代码:

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
    }

或者,如果您有办法在整个应用程序中共享状态(也许是单例),则可以避免使用 UserDefaults 并将其保存为您使用的任何 class 的成员。