B.Saravana Kumar
B.Saravana Kumar

Reputation: 1242

iOS Convert NSData to NSDictionary returns nil?

In My code I want to convert NSData to NSDictionary but it returns nil I don't know what mistake I made,I Used NSJSONSerialization for convert data to dictionary, The NSData was received from server response.

Here I show my Full code what I am trying.

-(void)SendPushNotification:(NSString*)getUrl :(NSMutableDictionary *)getData withCompletionBlock:(void(^)(NSDictionary *))completionBlock
{
    NSError *error;

NSLog(@"dict val: %@",getData);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:getData options:NSJSONWritingPrettyPrinted error:&error];// Pass 0 if you don't care about the readability of the generated string
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSString *postLengthas = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:getUrl]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];

NSString *chkRegDevice= [[NSUserDefaults standardUserDefaults] stringForKey:@"bearer"];
NSString *strfds=[NSString stringWithFormat:@"bearer %@",chkRegDevice];
[request setHTTPMethod:@"POST"];
[request setValue:postLengthas forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:strfds forHTTPHeaderField:@"Authorization"];
[request setHTTPBody:postData];

NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){
    if(error)
    {
        NSLog(@"%@", [error localizedDescription]);
        completionBlock(nil);
    }else{
        NSError *jsonError;
        NSString *clientDetail = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSLog(@"clientDetail: %@", clientDetail);
        NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa options:NSJSONReadingMutableContainers error:&jsonError];
        NSLog(@"json %@",json);
        if (![clientDetail isEqualToString:@"Object reference not set to an instance of an object."]) {
            if (completionBlock) {
                completionBlock(json);
            }
        }
        else
        {
            completionBlock(nil);
        }
     }
  }];
 [taskk resume];
}

Here the following response I get to convert NSData to NSString.

"{\"multicast_id\":8856529321585625357,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1534479035021563%1dbdaa031dbdaa03\"}]}"

Upvotes: 0

Views: 1352

Answers (3)

Phineas Huang
Phineas Huang

Reputation: 833

Try this.

NSString* str = your string data;
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *decodeString = [[NSString alloc] initWithData:data 
   encoding:NSASCIIStringEncoding];

NSDictionary *dict = [self dictionaryWithJsonString:decodeString];

/////////////////////

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

    options:NSJSONReadingMutableContainers
                                                      error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

Upvotes: 0

Mukesh
Mukesh

Reputation: 797

Try the following code:

NSError* error;
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa
                                                 options:kNilOptions 
                                                   error:&error];
NSLog(@"JSON DICT: %@", json);

Upvotes: 0

Puneet Sharma
Puneet Sharma

Reputation: 9484

Pass NSData object(data) directly to JSONObjectWithData. Also, to check the error, you can print jsonError.

Upvotes: 0

Related Questions