xcode 不支持的 URL iOS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28267557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:35:12  来源:igfitidea点击:

Unsupported URL iOS

iosobjective-cxcodehttpurl

提问by Nicole SD

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

我有一个有效的 url,但我得到 - 不支持的 url 错误。谁能告诉我为什么?

As you can see there is http://

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

这就是我尝试初始化 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"]];

回答by zaph

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

URL 不能包含不在 ASCII 字符集中的字符,这些字符必须被转义。

Use stringByAddingPercentEncodingWithAllowedCharacterswith the character-set URLQueryAllowedCharacterSet

使用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);

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

请参阅 URL 编码文档的字符集