iOS: NSString loses URL, (null) is shown

2019-08-11 04:34发布

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??

2条回答
Ridiculous、
2楼-- · 2019-08-11 05:17

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.

查看更多
Emotional °昔
3楼-- · 2019-08-11 05:37

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.

查看更多
登录 后发表回答