URLWithString:返回nil

gca*_*amp 93 iphone url objective-c nsurl nsstring

它可能很容易,但我似乎没有找到为什么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];
Run Code Online (Sandbox Code Playgroud)

ger*_*ry3 201

您还需要转义硬编码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];
Run Code Online (Sandbox Code Playgroud)

您可以删除localisationName的转义,因为它将通过转义整个字符串来处理.

  • 以上 API 已弃用。您可以使用以下 API `webStringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];` (3认同)

Isl*_*him 40

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

NSURL *_url = [NSURL fileURLWithPath:path];
Run Code Online (Sandbox Code Playgroud)


Yuj*_*uji 8

我猜你需要用-[NSString stringByAddingPercentEscapesUsingEncoding:].请参阅Apple doc.

另一个评论是,作为旧计时器,我发现将非ASCII字符放在源文件中有点不安.也就是说,这个Apple医生说,从10.4开始,UTF-16字符串就可以了@"...".不知何故,GCC似乎正确地将Latin-1中的源文件转换为二进制文件中的UTF-16,但我认为仅在源代码中使用7位ASCII字符是最安全的,并使用NSLocalizedString.