2009-12-30 143 views
87

它可能很容易,但我似乎没有找到为什么URLWithString:返回零这里。URLWithString:返回零

//localisationName is a arbitrary string here 
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSString* stringURL = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false&key=", webName]; 
NSURL* url = [NSURL URLWithString:stringURL]; 
+1

是什么在调用'stringWithFormat:'之前'webName'的值? 然后,在调用'URLWithString:'之前'stringURL'的值是多少? 使用'NSLog()'将它们一步一步地打印出来,或者设置断点并检查它们设置的值。 – 2009-12-30 17:38:30

回答

189

你需要逃避非ASCII字符在您的硬编码的网址,以及:

//localisationName is a arbitrary string here 
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSString* stringURL = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName]; 
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSURL* url = [NSURL URLWithString:webStringURL]; 

你或许可以去除localisationName的转义,因为它会被整个字符串转义处理。

+0

Thnx其工作正常......... – 2011-04-05 04:36:58

+0

其工作....好 – Akshay 2013-11-08 10:49:22

+0

试图了解为什么URLWithString在这里给零。 Apple文档说“必须是符合RFC 2396的URL”。该方法根据RFC 1738和1808解析URLString。“做一些阅读... – russau 2014-02-02 16:19:36

8

我想你需要使用-[NSString stringByAddingPercentEscapesUsingEncoding:]。请参阅Apple doc

另一个意见是,作为一个老计时器,我觉得把非ASCII字符放在源文件中有点不安。 这就是说,这个Apple doc表示,从10.4开始,在@"..."里面的UTF-16字符串可以。 不知何故,GCC似乎正确地将Latin-1中的源文件转换为二进制文件中的UTF-16,但我认为只在源代码中使用 7位ASCII字符并且使用NSLocalizedString是最安全的。

2

我觉得你的重音字符扔东西了;他们不会被-stringByAddingPercentEscapesUsingEncoding处理。

0

如果传递给它的字符串格式不正确,则URLWithString:call将返回nil。 由于NSURL为错误的URL返回nil,因此请NSLog记录您的字符串并设置断点以准确查看传递给您的NSURL创建方法的内容。如果你的URLWithString与一个硬编码值一起工作,这进一步证明了你传递的任何东西都是畸形的。 see

0

您可以直接使用NSURL而不使用NSString。

//.h文件

@interface NewsBrowser : UIViewController { 

    UIWebView *webView; 
    NSURL *NewsUrl; 

} 

@property (nonatomic, retain) IBOutlet UIWebView *webView; 

@property(nonatomic,assign)NSURL *NewsUrl; 

@end 

//.m文件

[webView loadRequest:[NSURLRequest requestWithURL:NewsUrl]]; 

和I(使用NewsUrl变量)将URL传递从另一视图这种观点。

试试吧。

+0

这个答案没有解决的问题可言,这是问为什么URLWithString:返航为零。 (此外,您甚至没有显示将字符串更改为URL的方式。) – ArtOfWarfare 2013-04-13 00:27:58

37

如果您处理保存在文件管理器上的文件,请使用此功能。

+0

感谢那就是我一直在寻找的东西。 – user1258240 2014-03-23 21:15:31

+0

这也适用于我 – ekscrypto 2014-04-22 14:07:10

+0

这是一个优秀和简洁的解决方案,谢谢! – ThinkBonobo 2014-05-19 21:24:11

2

NSURL URLWithString:@“”将返回nil,如果网址不符合RFC 2396,如果你通过在链接rfc2396读,你会得到的细节

负荷因此必须转义

一个伟大的网站,我发现这里检查有问题的字符,选择URL路径选择

http://www.websitedev.de/temp/rfc2396-check.html.gz