简体   繁体   English

如何在UserDefault中存储推送通知警报消息?

[英]How can I store Push Notification alert message in UserDefault?

I want to build an app that I can receive push notification and save inside client device for limit 25 Notification. 我想构建一个可以接收推送通知并保存在客户端设备中的应用程序,以限制25个通知。 If application running and may not running. 如果应用程序正在运行并且可能未运行。 How can I stored PushNotification alert message?. 如何存储PushNotification警报消息? If app running that time arrived Notification alert message stored in UserDefault but when app in background or Inactive state that time not stored Notification alert message in UserDefault. 如果运行该时间的应用程序到达时,通知警报消息存储在UserDefault中,但是当应用程序处于后台或非活动状态时,该时间未在UserDefault中存储通知警报消息。 I want to know that I need to use UserDefault or CoreData to store the Push Notification message inside client app or not? 我想知道是否需要使用UserDefault或CoreData在客户端应用程序内部存储推送通知消息? If it is not, what should I use? 如果不是,我应该怎么用? I really need a hand to pick me up. 我真的需要一只手来接我。

Please Help. 请帮忙。 Thanks. 谢谢。

STEP 1: 步骤1:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
     {
         requestUserPermissions(application: application)
         if let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: AnyObject]
            {
                let info : NSDictionary! = notification as NSDictionary
                if info != nil
                {
                    getDataFromNotification(userInfo: info as! [AnyHashable : Any])
                    Alert.showAlert((self.window?.rootViewController)!, message: "App is terminated", strtitle: "Notification")
                }
            }
            return true
    }

STEP 2: 第2步:

func requestUserPermissions(application: UIApplication)
    {
        if #available(iOS 10.0, *)
        {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.badge, .alert, .sound])
            {
                (granted, error) in

                if( !(error != nil) )
                {
                    application.registerForRemoteNotifications()
                }
                // Enable or disable features based on authorization.
            }

        }
        else {
            // Fallback on earlier versions
            if (!application.isRegisteredForRemoteNotifications)
            {
                application.applicationIconBadgeNumber = 0
                application.registerForRemoteNotifications()
            }
        }

STEP 3: 步骤3:

@objc(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:) @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
 {

       print("Userinfo1 \(response.notification.request.content.userInfo)")
        getDataFromNotification(userInfo: response.notification.request.content.userInfo)
        Alert.showAlert((self.window?.rootViewController)!, message: "I am in Background", strtitle: "Notification")
    }
      @objc(userNotificationCenter:willPresentNotification:withCompletionHandler:) @available(iOS 10.0, *)
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
        {
           print("Userinfo2 \(notification.request.content.userInfo)")
            getDataFromNotification(userInfo: notification.request.content.userInfo)
            Alert.showAlert((self.window?.rootViewController)!, message: "I am in forground", strtitle: "Notification")
        }

STEP 4: 第四步:

func getDataFromNotification(userInfo: [AnyHashable : Any])
    {
        let info : NSDictionary! = userInfo as NSDictionary

        if info != nil
        {
            if let aps = info["aps"] as? NSDictionary
            {
               if let resultsDict =  aps as? [String:AnyObject]
             {
                for _ in resultsDict
               {
                let str = dictCleanData.value(forKey: "alert")!
                let time = dictCleanData.value(forKey: "day")!

                let dict = ["msg" : str, "time": time]

                UserDefaults.standard.set(dict, forKey: "dict")
                UserDefaults.standard.synchronize()

                  }
             }
           }
     }
}

STEP 5: TO check saved data on Other view controller 步骤5:在其他视图控制器上检查保存的数据

 override func viewDidLoad()
 {
        super.viewDidLoad()

           if UserDefaults.standard.value(forKey: "dict") != nil
          {
             let dict : NSDictionary = UserDefaults.standard.value(forKey: "dict") as! NSDictionary

               arr_Veges.add(dict)

               if  UserDefaults.standard.value(forKey: "arr_Veges") != nil
               {
                  let arr = UserDefaults.standard.value(forKey: "arr_Veges") as! NSArray

                  for oldObj in arr
                  {
                    arr_Veges.add(oldObj)
                  }
               }

               UserDefaults.standard.set(arr_Veges, forKey: "arr_Veges")
               UserDefaults.standard.synchronize()
        }
}

In my opinion you can use NSUserDefaults to store user related information. 我认为您可以使用NSUserDefaults来存储与用户相关的信息。 Push Notifications in your case. 根据您的情况推送通知。 However, just a thought, you can simple append the notifications to local storage or a txt file on user device and remove the element as user accesses it. 但是,仅考虑一下,您可以简单地将通知追加到用户设备上的本地存储或txt文件中,并在用户访问元素时将其删除。

But this will only work when user is using the app. 但这仅在用户使用应用程序时有效。 In case you want to make this work even when the app is not working, you need to make a backend and store these data in some kind of cloud database. 如果即使在应用程序无法运行时也要使此工作正常进行,则需要创建一个后端并将这些数据存储在某种云数据库中。 You can extract the records from data and push again to NSUserDefaults or local txt file when the app is turned on again. 您可以从数据中提取记录,并在再次打开应用程序时再次将NSUserDefaults推送到NSUserDefaults或本地txt文件。

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

相关问题 如何将用户从推送通知警报重定向到App Store上的应用程序? - How to redirect users to app on the App Store from push notification alert? 将推送通知数据存储到 UserDefault iOS Swift - Storing Push Notification Data into UserDefault iOS Swift 如何通过代码打开推送通知? - How can I turn on push notification by code? 如果用户在警报中将磁带“关闭”,则捕获推送通知的消息 - Catch push notification's message if the user tapes “close” in the alert 如何在没有警报的情况下发送Parse推送通知? - How to send a Parse push notification without an alert? 如何防止IOS推送通知的系统警报 - How to prevent system alert for IOS push notification iOS有什么方法可以在收到通知后修改推送通知警报消息? - iOS any way to modify push notification alert message once received? 在iOS应用上显示推送通知作为提醒消息[phonegap / cordova] [Pushwoosh] - Display push notification as alert message on iOS app [phonegap/cordova][Pushwoosh] 如何使用用户默认Swift 4存储和检索表数据 - How to store and retrieve tabledata using userdefault Swift 4 我应该如何在 swift UI 中使用 NS Userdefault 存储用户名 - how should i store user name using NS Userdefault in swift UI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM