不受支持的URL iOS

时间:2015-02-01 20:36:09

标签: ios objective-c xcode http url

我有一个有效的网址,我得到了 - 不支持的网址错误。可以告诉我有人为什么?

如您所见,有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}

这就是我尝试初始化网址的方式:

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

方法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 个答案:

答案 0 :(得分:30)

网址不能包含不在ASCII字符集中的字符,必须对这些字符进行转义。

stringByAddingPercentEncodingWithAllowedCharacters与字符集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);

输出:

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

请参阅网址编码的字符集Documentation