NSString to NSurl

2019-02-01 08:10发布

having trouble getting NSSTRING to convert to NSURL, item.image, holds the url for an image that im getting through xml

NSString *urlString = [NSString stringWithFormat:@"%@", item.image];
NSURL *url = [NSURL URLWithString:urlString];

NSLog(@"string> %@ ", urlString);
NSLog(@"url> %@ ", url);

2011-06-23 11:18:49.610 Test[10126:207] string> http://www.harlemfur.com/images/Dog_Olive.jpg       
2011-06-23 11:18:49.611 Test[10126:207] url> (null) 

also if i try :

NSString *urlString = [NSString stringWithFormat:@"%@", item.image];
NSURL *url = [NSURL fileURLWithPath :urlString];

2011-06-23 11:22:08.063 Test[10199:207] string> http://www.harlemfur.com/images/Dog_Olive.jpg

2011-06-23 11:22:08.064 Test[10199:207] url> %0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.harlemfur.com/images/Dog_Olive.jpg%0A%20%20%20%20%20%20%20%20%20%20%20%20 -- / 

4条回答
该账号已被封号
2楼-- · 2019-02-01 08:29

When making URL from NSString, don't forget to encode it first, so try this:

NSString *urlString = [NSString stringWithFormat:@"%@", item.image];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];  

For IOS ≥ 9.0 use

NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
查看更多
Explosion°爆炸
3楼-- · 2019-02-01 08:35

In Swift:

NSURL(fileURLWithPath: item.image!)
查看更多
迷人小祖宗
4楼-- · 2019-02-01 08:40

item.image does not only contain the URL, but it starts with a newline and spaces. Remove those first and you should be fine.

查看更多
再贱就再见
5楼-- · 2019-02-01 08:53

All is ok, if you want to get the URL to print in NSLog use this:

NSLog(@"url> %@ ", [url absoluteString]);
查看更多
登录 后发表回答