0

I'm trying to fetch an image from a url and show it in ImageView. The image is encoded in base64Encoded Data. I am using following code for it

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url scale:2.0];

[ImageView setImage: image];

Can any one suggest what is the problem in it.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Guri
  • 85
  • 1
  • 1
  • 9

3 Answers3

0

One strong possibility is that dataWithContentsOfURL failed for whatever reason. You should use dataWithContentsOfURL:options:error: instead and perform some error handling.

Edit:

In fact, you shouldn't use the NSData methods at all for downloading image data. The Apple docs especially state that they are only suitable for local resources and recommend that you use this NSURLSession method when downloading: (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler

Clafou
  • 15,250
  • 7
  • 58
  • 89
0

May it doesn't work because you have to log in to see the image from the URL you referenced in your code-snippet.
If I try to view the image from the URL it tells me to log in.

lukas
  • 2,300
  • 6
  • 28
  • 41
  • Yes its working fine. I have reinstall the app in simulator after deleting previous one – Guri Apr 14 '14 at 13:17
0

Try these two methods.they are both from here:how to decode BASE64 encoded PNG using Objective C

You can decode it to NSData using this:

-(NSData *)dataFromBase64EncodedString:(NSString *)string{
    if (string.length > 0) {

        //the iPhone has base 64 decoding built in but not obviously. The trick is to
        //create a data url that's base 64 encoded and ask an NSData to load it.
        NSString *data64URLString = [NSString stringWithFormat:@"data:;base64,%@", string];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]];
        return data;
    }
    return nil;
}

Then use this to get the image:

-(void)imageFromBase64EncodedString{

    NSString *string = @"";  // replace with encocded string
    NSData *imageData = [self dataFromBase64EncodedString:string];
    UIImage *myImage = [UIImage imageWithData:imageData];

    // do something with image
}

2nd method you can use:

You can download class files from http://projectswithlove.com/projects/NSData_Base64.zip

Then #import "NSData+Base64.h"

put this is your code

NSData *data = [[NSData alloc] initWithData:[NSData dataWithBase64EncodedString:strData]];

You can now convert to UIImage

UIImage *image = [UIImage imageWithData:data];
Community
  • 1
  • 1
Steve Sahayadarlin
  • 1,164
  • 3
  • 15
  • 32