Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL is null while NSString is correct in Objective-C

I have an NSString containing a url and when I allocate NSURL with the NSString, NSURL outputs (null). It's because there are some illegal characters in the url, which NSURL can't read without encoding the NSString containing the url.

NSString *u = [incomingUrlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:u];

NSLog(@"INCOMINGURLSTRING: %@" , u);
NSLog(@"URL: %@" , url);

Output is:

 INCOMINGURLSTRING: /url/path/fileName_blå.pdf
 URL: (null)

incomingUrlString contains the Norwegian letter "å", which I think is the reason for the NSURL being (null)

I also tried this:

NSString *trimmedString = [file stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)trimmedString, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", kCFStringEncodingUTF8);

NSLog(@"TRIMMEDSTRING: %@" , trimmedString);
NSLog(@"ENCODEDSTRING: %@" , [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);

NSURL *url = [NSURL URLWithString:encodedString];

NSLog(@"URL: %@" , url);

Here the output is:

 TRIMMEDSTRING: /url/path/fileName_blå.pdf
 ENCODEDSTRING: /url/path/fileName_blå.pdf
 URL: %2Furl%2FPath%2FfileName_bl%C3%A5.pdf

My goal is to load the URL into a UIWebView. It works for all the other incoming urls except for this one, they all look the same except for the filename. This is the only one containg an illegal character. But I have to find a way to encode this, because there will be more files containg either "æ", "ø" or "å" in the future.

I know the output does not look correct according to url standards, which I did on purpose. I can't show the correct url with http://blah blah because of security reasons.

Can anyone help?

like image 405
Magnus Avatar asked Dec 13 '11 08:12

Magnus


2 Answers

The method you're using for percent-encoding the characters in the string also escapes legal URL characters. This would be appropriate if you were encoding a URL parameter, in this case though it would be better to simply use stringByAddingPercentEscapesUsingEncoding: because it leaves the characters that are part of the URL's structure (':', '/', etc.) intact:

NSString *u = @"http://example/path/fileName_blå.pdf";
u = [u stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:u];
NSLog(@"%@", url); // http://example.com/path/fileName_bl%C3%A5.pdf
like image 194
omz Avatar answered Sep 28 '22 17:09

omz


If you have an URL that is a file path you must use + (id)fileURLWithPath:(NSString *)path. For the URLWithString: method the String must contain a scheme like file:// or http://.

like image 23
V1ru8 Avatar answered Sep 28 '22 17:09

V1ru8