NSString to NSurl

user616860 picture user616860 · Jun 23, 2011 · Viewed 41k times · Source

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

Answer

cxa picture cxa · Jun 23, 2011

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]]];