0

Maybe this question title is not very clear. I have json as follow:

// {
//    "aps": {
//        "alert": {
//            "title":"nice title",
//            "body":"A nice body. $savings"
//        },
//        "content-available":"1"   //This flag set enables background processing
//    },
//    "blabla":"1",
//    "spend_amount":"$cash",
//    "save_amount":"$savings"
// }           

To get info inside title I need to do either:

 NSString * _message = [[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];

or define three two variables

id payload = [userInfo objectForKey:@"aps"];
id alert = [payload objectForKey:@"alert"];
NSString * _actionTitle = [alert objectForKey:@"title"];

Is there any nicer way to do this?

Bernard
  • 4,240
  • 18
  • 55
  • 88

2 Answers2

3

Try to use following one line of code for getting nested Dictionary keys value:

[userInfo valueForKeyPath:@"aps.alert.title"];

I just Create and example and test code:

    NSMutableDictionary *d =[[NSMutableDictionary alloc]init];
    [d setValue:@"A nice body. $savings" forKey:@"body"];
    [d setValue:@"nice title" forKey:@"title"];


    NSMutableDictionary *b =[[NSMutableDictionary alloc]init];
    [b setValue:d forKey:@"alert"];

    NSMutableDictionary *e =[[NSMutableDictionary alloc]init];

    [e setValue:@"1" forKey:@"content-available"];
    [e setValue:b forKey:@"aps"];

    NSLog(@"Dictioarn = %@",e);
    NSLog(@"Dictioarn = %@",[e valueForKeyPath:@"aps.alert.title"]);

OUTPUT IS:

Dictioarn = nice title
Nitin Gohel
  • 49,482
  • 17
  • 105
  • 144
0

Use this code,

change objectForKey instead of valueForKey in body keyword,

NSString * _message = [[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] valueForKey:@"body"];

hope its helpful

Iyyappan Ravi
  • 3,205
  • 2
  • 16
  • 30