【问题标题】:NSURL and URL ValidityNSURL 和 URL 有效性
【发布时间】:2023-03-18 09:18:01
【问题描述】:

我正在使用来自 API 的 URL,其中搜索词被引号括起来。例如: http://www.example.com/searchterm="search".

但是,由于引号的原因,由于 URL 无效,我的 NSURL(由 URLWithString 生成)为 nil。有没有解决的办法?谢谢!

【问题讨论】:

    标签: iphone objective-c ios nsurl


    【解决方案1】:

    可以在引号前加反斜杠,或者URL编码值%22

    http://www.example.com/searchterm=\"search\"

    http://www.example.com/searchterm=%22search%22

    或者您可以在将其用作 NSURL 之前删除引号。

    NSString * searchUrl = @"http://www.example.com/searchterm=\"search\"";
    searchUrl = 
      [searchUrl stringByReplacingOccurrencesOfString:@"\"" withString:@""]; // something to this effect, not tested.
    

    然后你就可以进行正常的 NSURL 调用了:

    [NSURL URLWithString: searchUrl];
    

    【讨论】:

    • 我这样做了。这就是我得到初始字符串的方式。但后来我尝试了NSURL *URL = [NSURL URLWithString:URLString];,它返回 nil(即使 URLString 是正确的)
    【解决方案2】:

    尝试以下方法:

    #define SAFARI_SEARCH_URL_FORMAT @"http://search/search?q=\"%@\""
    mySearchBar.text =@"hello";
    NSString * tempstr = [NSString stringWithFormat:SAFARI_SEARCH_URL_FORMAT, mySearchBar.text];
    
        NSURL *an1Url = [[[NSURL alloc] initWithString:[tempstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
    ] autorelease];
    NSLog(@"--(%@)--",an1Url);
    

    an1Url 不会为零

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-22
      • 2011-07-19
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      相关资源
      最近更新 更多