How can I store Push Notification alert message in UserDefault?

白昼怎懂夜的黑 提交于 2019-12-18 08:10:23

问题


I want to build an app that I can receive push notification and save inside client device for limit 25 Notification. If application running and may not running. How can I stored PushNotification alert message?. 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. I want to know that I need to use UserDefault or CoreData to store the Push Notification message inside client app or not? If it is not, what should I use? I really need a hand to pick me up.

Please Help. Thanks.


回答1:


STEP 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:

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:

@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

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



回答2:


In my opinion you can use NSUserDefaults to store user related information. 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.

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.



来源:https://stackoverflow.com/questions/41035878/how-can-i-store-push-notification-alert-message-in-userdefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!