filou
filou

Reputation: 1619

iOS: NSString loses URL, (null) is shown

This is my Code so far:

NSString *listedImageURL = listedProduct.image;

NSLog(@"URL: %@", listedImageURL);

This Code works fine and NSLog shows me the correct URL. But when I try the following Code, NSLog shows up (null):

NSString *listedImageURL = listedProduct.image;

NSURL *imageURL = [NSURL URLWithString:listedImageURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

What am I doing wrong??

Upvotes: 1

Views: 1854

Answers (2)

Keab42
Keab42

Reputation: 688

I believe that relower is on the right track, the documentation states:

This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.

I believe that it would be helpful to identify which characters might be causing an issue for you if you were to post some examples of the URLs that you are converting.

I would suggest logging: listedImageURL

and then also running:

NSString *escapedImageUrl = [listedProduct.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

then log that.

That should let you see what is being escaped and what is being missed. It can be something as simple as a stray space.

You could also try using NSASCIIStringEncoding instead of NSUTF8StringEncoding and see if that makes a difference.

Upvotes: 5

relower
relower

Reputation: 1313

it can be null, because of your string to url convertion.

Try this code below;

NSString *listedImageURL = [listedProduct.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imageURL = [NSURL URLWithString:listedImageURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

will work for you i think. good luck.

Upvotes: 2

Related Questions