URLWithString:返回nil

这可能很容易,但我似乎没有find为什么是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]; 

您还需要在硬编码url中转义非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的转义,因为它将通过整个string的转义来处理。

如果您处理保存在文件pipe理器上的文件,请使用此function。

 NSURL *_url = [NSURL fileURLWithPath:path]; 

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

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

我觉得你的重音字符正在丢掉东西。 他们不会被-stringByAddingPercentEscapesUsingEncoding处理。

NSURL URLWithString:如果URL不符合RFC 2396,则返回nil,且必须转义

如果你通过链接阅读rfc2396 ,你会得到大量的细节

我发现一个很棒的网站,用来检查有问题的字符,selectURL的path选项

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

如果传递给它的string格式不正确,URLWithString:call将返回一个零。 由于NSURL为错误的URL返回nil,所以NSLoglogging你的string并设置断点,以确切地看到传递给你的NSURL创build方法的内容。 如果你的URLWithString与一个硬编码的值一起工作,这进一步certificate,无论你传递的是畸形的。 看到

你可以直接使用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]]; 

而且我从另一个视图(使用NewsUrlvariables)传递URL到这个视图。

尝试一下。