【问题标题】:+ (instancetype) URLWithString returns nil when I try to put non-latin character+ (instancetype) URLWithString 在我尝试输入非拉丁字符时返回 nil
【发布时间】:2018-04-19 11:16:00
【问题描述】:

我知道我遇到了什么错误,但是我不知道如何决定它。在我的 Cocoa App 中遇到Þþ, Ðð, Ææ 等字母是可以的。

通过我放置的断点,我发现URLWithString 每次放置至少一个非拉丁字符时都会返回 nil。否则,返回一些仅基于拉丁字符的新 URL。

尝试的一些片段:

NSString *baseURLString = @"https://hostdomain.com";
NSString *pathURLString = @"/restapi/someRequest?par1=arg1&par2=arg2&input=";
NSString *fullURLString = [NSString stringWithFormat:@"%@%@móðir", baseURLString, pathURLString];
NSURL *url = [NSURL URLWithString:fullURLString]; // here I get a nil while working with non-latin characters.

我仍在努力寻找解决方案,但这里关于 stackoverflow 的所有决定都对我没有帮助。任何想法将不胜感激!我的想法是 URLWithString 仅适用于 ASCII 符号.. ????

【问题讨论】:

    标签: objective-c utf-8 nsstring nsstringencoding


    【解决方案1】:

    URLWithString 仅适用于有效的 URL。您传递的某些字符对于 URL 的查询部分无效。见section 2 of RFC 3986。由于 URL 无效,因此返回 nil。

    如果您的 URL 中有任意字符,则不应尝试将其全部构建为单个字符串,因为 URL 的每个部分都需要不同的编码。您需要使用NSURLComponents。这将自动正确地转义每个部分。

    NSURLComponents *comp = [NSURLComponents new];
    comp.scheme = @"https";
    comp.host = @"hostdomain.com";
    comp.path = @"/restapi/someRequest";
    comp.query = @"par1=arg1&par2=arg2&input=óðir";
    
    NSURL *url = comp.url;
    // https://hostdomain.com/restapi/someRequest?par1=arg1&par2=arg2&input=%C3%B3%C3%B0ir
    

    或者,由于 URL 的基本部分是静态的,并且您知道它的编码正确,您可以这样做:

    NSURLComponents *comp = [NSURLComponents componentsWithString:@"https://hostdomain.com/restapi/someRequest"]
    comp.query = @"par1=arg1&par2=arg2&input=óðir"
    

    如果你真的想更直接地构建字符串,你可以看看stringByAddingPercentEncodingWithAllowedCharacters:。查询部分使用[NSCharacterSet URLQueryAllowedCharacterSet]

    【讨论】:

      猜你喜欢
      • 2015-07-30
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2010-12-12
      • 2011-01-07
      • 2015-06-26
      • 2013-01-23
      • 2015-03-24
      相关资源
      最近更新 更多