简体   繁体   English

swift 安排本地通知

[英]Scheduling local notifications in swift

In my app I applied a code that stops a notification being sent every time user goes to a specific view controller, but now the notification is sent only once at the very beginning after download.在我的应用程序中,我应用了一个代码,每次用户转到特定视图 controller 时都会停止发送通知,但现在通知仅在下载后的最开始发送一次。 How can I change it to show the notification only once each time after the app had been refreshed?如何将其更改为每次刷新应用后仅显示一次通知? Here's the code:这是代码:

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])
          
        
        }
    }
    

    
    

When you store something to UserDefaults, it stays even after the app closes.当您将某些内容存储到 UserDefaults 时,即使在应用程序关闭后它也会保留。 That's why the notification doesn't show again.这就是通知不再显示的原因。

If you don't want it to be persisted across app launches, you should set it to false at the app launch time (I assume that's what you mean by refreshed):如果您不希望它在应用程序启动时持续存在,则应在应用程序启动时将其设置为false (我假设这就是您所说的刷新的意思):

You can add this to your UIApplicationDelegate (or add the line to existing didFinishLaunchingWithOptions):您可以将此添加到您的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
    }

Or, if you have a way of sharing state throughout the app (singleton perhaps), you can avoid UserDefaults and save it as a member of whatever class you use.或者,如果您有办法在整个应用程序中共享 state(也许是单例),则可以避免 UserDefaults 并将其保存为您使用的任何 class 的成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM