NSString to NSurl
41,240
Solution 1
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]]];
Solution 2
All is ok, if you want to get the URL to print in NSLog use this:
NSLog(@"url> %@ ", [url absoluteString]);
Solution 3
item.image
does not only contain the URL, but it starts with a newline and spaces. Remove those first and you should be fine.
Related videos on Youtube
Author by
user616860
Updated on July 09, 2022Comments
-
user616860 almost 2 years
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 -- /
-
Eiko almost 13 yearsCannot reproduce. The problem must be with item.image. What type is it exactly?
-
Eiko almost 13 yearsDo these lines appear in your code just like that? Directly one after another (constructing and logging)?
-
-
user616860 almost 13 yearsthanks but this is the print out im getting :2011-06-23 11:41:34.796 Test[10609:207] string> harlemfur.com/images/Dog_Olive.jpg 2011-06-23 11:41:34.797 Test[10609: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
-
Eiko almost 13 yearsYou can print objects directly in Objective-C. It calls the
description
method. Works fine with NSURL. -
cxa almost 13 yearsThen you should check your item.image, make sure there is no hidden character. Checkout NSString documentation to see how to trim string.
-
user616860 almost 13 yearsyou were right, i had extra spaces in my xml, thanks dude, works like a charm
-
Laurenswuyts over 7 yearsJust a quick update, stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding is deprecated for IOS ≥ 9.0. You should use: stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]