简体   繁体   中英

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. 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. 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):

You can add this to your UIApplicationDelegate (or add the line to existing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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