iOS: NSString loses URL, (null) is shown

白昼怎懂夜的黑 提交于 2019-12-14 02:29:21

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10851314/ios-nsstring-loses-url-null-is-shown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!