Unsupported URL iOS

2019-03-19 23:05发布

问题:

I have a valid url and i get - unsupported url error. Can tell me somebody why?

As you can see there is http://

// http://fr.radiovaticana.va/news/2015/02/01/le_pape_fran%C3%A7ois_%C3%A0_sarajevo_le_6_juin_prochain/1121065

Error description=Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x78f97920 {NSUnderlyingError=0x79f78bd0 "unsupported URL", NSLocalizedDescription=unsupported URL}

This is how i was trying to init the url :

Method 1 :

NSString *path=@"http://fr.radiovaticana.va/news/2015/02/01/le_pape_françois_à_sarajevo_le_6_juin_prochain/1121065";
NSURL *url=[NSURL URLWithString:path];
NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:url];

Method 2 :

NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://fr.radiovaticana.va/news/2015/02/01/le_pape_françois_à_sarajevo_le_6_juin_prochain/1121065"]];

回答1:

URL's can not contain characters that are not in the ASCII character-set, such characters must be escaped.

Use stringByAddingPercentEncodingWithAllowedCharacters with the character-set URLQueryAllowedCharacterSet

NSString *path = @"http://fr.radiovaticana.va/news/2015/02/01/le_pape_françois_à_sarajevo_le_6_juin_prochain/1121065";
NSString *escapedPath = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSLog(@"escapedPath: %@", escapedPath);

Output:

escapedPath: http://fr.radiovaticana.va/news/2015/02/01/le_pape_fran%C3%A7ois_%C3%A0_sarajevo_le_6_juin_prochain/1121065\

See Character Set for URL Encoding Documentation