簡體   English   中英

swift 安排本地通知

[英]Scheduling local notifications in swift

在我的應用程序中,我應用了一個代碼,每次用戶轉到特定視圖 controller 時都會停止發送通知,但現在通知僅在下載后的最開始發送一次。 如何將其更改為每次刷新應用后僅顯示一次通知? 這是代碼:

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
    }

或者,如果您有辦法在整個應用程序中共享 state(也許是單例),則可以避免 UserDefaults 並將其保存為您使用的任何 class 的成員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM