【问题标题】:How can I store Push Notification alert message in UserDefault?如何在 UserDefault 中存储推送通知警报消息?
【发布时间】:2016-12-08 09:25:31
【问题描述】:

我想构建一个应用程序,我可以接收推送通知并保存在客户端设备中以获取限制 25 通知。如果应用程序正在运行并且可能未运行。如何存储 PushNotification 警报消息?如果运行该时间的应用程序到达存储在 UserDefault 中的通知警报消息,但当应用程序处于后台或非活动状态时,该时间未将通知警报消息存储在 UserDefault 中。我想知道是否需要使用 UserDefault 或 CoreData 将推送通知消息存储在客户端应用程序中?如果不是,我应该使用什么?我真的需要一只手来接我。

请帮忙。谢谢。

【问题讨论】:

  • 如果不打开推送通知,您将无法处理它。我的建议,请改为将通知发送到服务器上的每个设备
  • @h44f33z 我可以以任何其他方式将到达通知存储在 UserDefualt 或 CoreDate 中吗?
  • 对我来说,它不是关于“在哪里”保存它,但这里的问题是你无法检查推送通知,除非你打开收到的通知。另外,如果你打开三个通知之一(比如说),你只能得到你打开的那个,其余的不会得到内容

标签: ios swift core-data push-notification nsuserdefaults


【解决方案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
    }

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

第 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")
        }

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

                  }
             }
           }
     }
}

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

【讨论】:

  • 应用程序未运行,通知数据未存储在 UserDefault 中。
  • 你想说什么?请解释。为了存储数据,您必须运行应用程序。 UserDefault 用于存储您的数据。即使用 UserDefaults,您可以查看以前和当前的数据。
  • 或者,如果我理解您在谈论应用程序何时处于后台或终止。是吗?
  • 是的。当应用程序在后台或终止时通知数据未存储。
  • 这段代码写在 AppDelegate 里面 := if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: AnyObject] { if let alertDict = remoteNotification["aps"] as? [AnyHashable: AnyObject] { if let alert = alertDict["alert"] { if let body = alert["body"] as? String { UserDefaults.standard.setValue(body, forKey: "Body") UserDefaults.standard.synchronize() } } } }
【解决方案2】:

在我看来,您可以使用NSUserDefaults 来存储用户相关信息。在您的情况下推送通知。但是,只是一个想法,您可以简单地将通知附加到本地存储或用户设备上的 txt 文件,并在用户访问它时删除该元素。

但这仅在用户使用应用程序时有效。如果您想在应用程序不工作的情况下进行这项工作,您需要创建一个后端并将这些数据存储在某种云数据库中。您可以从数据中提取记录并在应用再次打开时再次推送到NSUserDefaults或本地txt文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    相关资源
    最近更新 更多