Search code examples
objective-cnsarraynsdictionary

Unwrap array of dictionary


I have an array of dictionary from firebase like bellow :

"gcm.notification.data" = "{\"request\":\"update_location\",\"latitude\":\"45.48945419494574\",\"customMessage\":{\"loc-args\":[\"iPhone di Tester\"],\"loc-key\":\"LOCATION_CHECKIN\"},\"type\":\"checkin\",\"message\":\"Ggg\",\"longitude\":\"9.195329826333742\",\"child\":{\"name\":\"iPhone di Tester\",\"pid\":\"C312EDDC-E8A8-4EFC-9E65-957BE5DAC5FC\"}}";

I tried to unwrap the request, like bellow but it crash, can anyone help.

 NSDictionary *gcmnotificationdat = [userInfo objectForKey:@"gcm.notification.data"];
    NSString *request = [gcmnotificationdat objectForKey:@"request"];

Solution

  • You got a crash. As a developer it's important to read it. You can either understand it or not, but you can certainly look for it, and this one is quite known. It's a basic crash message that any iOS developer should know. If you don't, share it with us. You'll get better chances to get answers.

    The most important part being:

    -[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x100002090
    

    It means that you are trying to call a method objectForKey: on a NSString object. NSString doesn't know it, and that's why it crashes.

    The value of key gcm.notification.data is a JSON Stringified.

    So [userInfo objectForKey:@"gcm.notification.data"]; is in fact a NSString not a NSDictionary.

    Let's fix it now:

    //Creation of the sample for the sake of the test
    NSDictionary *userInfo = @{@"gcm.notification.data": @"{\"request\":\"update_location\",\"latitude\":\"45.48945419494574\",\"customMessage\":{\"loc-args\":[\"iPhone di Tester\"],\"loc-key\":\"LOCATION_CHECKIN\"},\"type\":\"checkin\",\"message\":\"Ggg\",\"longitude\":\"9.195329826333742\",\"child\":{\"name\":\"iPhone di Tester\",\"pid\":\"C312EDDC-E8A8-4EFC-9E65-957BE5DAC5FC\"}}"};
    
    //Parsing
    NSString *gcmNotificationJSONString = [userInfo objectForKey:@"gcm.notification.data"];
    NSData *gcmNotificationJSONData = [gcmNotificationJSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *gcmNotification = [NSJSONSerialization JSONObjectWithData:gcmNotificationJSONData options:0 error:nil];
    NSString *request = [gcmNotification objectForKey:@"request"];
    NSLog(@"Request: %@", request);
    

    Note: I removed the "dat" part of the var names, that you used because the key ends with "data" to not confuse NSString, NSData and NSDictionary as I explicitly named them from the class. I mistype a class in the comment, be careful and fix it from the code here.