【问题标题】:how to parse NSDictionary into NSUserDefaults IOS7如何将 NSDictionary 解析为 NSUserDefaults IOS7
【发布时间】:2014-05-26 11:25:53
【问题描述】:


在我的应用程序中,我想在UILabel 中显示远程通知。所以我正在尝试将通知消息从“Appdelegate”传递到我的故事板它不起作用请告诉我如何解决这个问题。

我的“Appdelegate”代码:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

  NSString *messag = [[userInfo description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];

 [[NSUserDefaults standardUserDefaults] setObject: messag forKey:@"message"];
 [[NSUserDefaults standardUserDefaults]synchronize];
 NSLog (@"message %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"message"]);
 UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
 personalnottypoliticalViewController *ringingVC = [mainstoryboard instantiateViewControllerWithIdentifier:@"notifymess"];

 [self.window setRootViewController: ringingVC];
 }

当我打印我的数据时,它会像这样:

message {
aps =     {
    alert = home;
    badge = 3;
    sound = "";
 };
}

在我的视图控制器中,我曾经这样使用过。

self.message.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"message"];
  NSLog (@"message %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"message"]);

在上述数据中,我只需要“警报”值如何获取警报值并将其存储到数据中,请告诉我是否可以这样做以及如何实现这一点。我在这里堆了很长时间,请不要给出一些想法来实现这一点。

谢谢。

【问题讨论】:

  • 您将其存储为 JSON 吗?
  • 找一些使用基类的教程,NSDictionary的例子:rypress.com/tutorials/objective-c/data-types/nsdictionary.html
  • @3r1d 不,我只需要存储在一个 NSString 数据中就可以了
  • 记录nsstring * message中的值-第一行值,这样可以帮助我们找到message的数据类型??

标签: ios objective-c nsdictionary


【解决方案1】:

description 方法为记录目的创建对象的字符串表示,但您不会以这种方式使用它来访问对象的内容。

来自 Apple 文档 -

userInfo 字典包含值为另一个值的 aps 键 字典。虽然你不应该需要aps中的信息 字典,您可以使用以下键检索其内容:

alert - 该值是警报消息的字符串或 字典有两个键:body 和 show-view。身体的价值 key 是一个字符串,包含警报消息和 show-view 键是一个布尔值。如果 show-view 键的值为 false,不显示警报的查看按钮。默认是显示 View 按钮,如果用户点击它,就会启动应用程序。

徽章 —A 数字表示要下载的数据项的数量 提供者。此数字将显示在应用程序图标上。缺席的 徽章属性的值表示当前标记的任何数字 图标应该被删除。

sound — 应用中声音文件的名称 捆绑播放作为警报声音。如果指定“默认”,则 应该播放默认声音。

因此,您可以使用此答案中的代码 - How to handle push notifications if the application is already running?

NSDictionary *aps=(NSDictionary *)[userInfo objectForKey:@"aps"];

NSString *message;

id alert = [aps objectForKey:@"alert"];
if ([alert isKindOfClass:[NSString class]]) {
   message = alert;
} else if ([alert isKindOfClass:[NSDictionary class]]) {
   message = [alert objectForKey:@"body"];
}

【讨论】:

    【解决方案2】:

    您好尝试使用此代码

    NSDictionary *dict=userInfo;

    NSString *messag=[[[dict objectForKey:@"message"]objectForKey:@"aps"]objectForKey:@"alert"];

    【讨论】:

      猜你喜欢
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多