Search code examples
iosiphoneobjective-ccocoa-touchnsdata

Is there any way to know which Class instance , NSData Object contains?


I have an NSData object which I obtained from a web server.

the contents of this data object are supposed to be a UIImage . but when i used it in the following code :-

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData * responseData, NSError *err) {

    if (err) {
        NSLog(@"Err %@",err.description);

    }else
    {

        if (responseData) 
        {
            NSLog(@"Data Length %d  ",[responseData length]);
            UIImage *img = [[UIImage alloc] initWithData:responseData];

            if (img) {
                NSLog(@"image in not null");
                self.imageView.image = img;
            }
            else
            {
                NSLog(@"image is null");
            }
        }

        else
        {
            NSLog(@"not returning anything");
        }
    }
}];

the out put says :-

Data Length 2786779
image is null

so i guess its not an Image

is there a way from which i could get to know which class instance does this NSData contains

PS:- I also used

NSLog("Description %@",data.description);

but it only generated a huge sequence of hex codes


Solution

  • Well.... it might be possible that your server is sending an image but its encoded.

    getting your UIImage *img = null doesn't necessarily mean that the response data is not an Image. if you aren't decoding it back, it will be null of course

    I think your response data is encoded in Base64...(most servers do)

    if so,...

    first download .h and .m files from this Link

    add and import them in your project.

    then use this code

    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataFromBase64String:str];
    UIImage *img = [[UIImage alloc] initWithData:data];
    

    this img will have your image. if your server is really sending an image.

    please note that.. not all of NSString *str in this code is representation of a UIImage it might be some part of it. and the rest can be information related to this image. so you have to decode only the image part of the response.

    hope this helps....