【发布时间】:2023-03-18 09:18:01
【问题描述】:
我正在使用来自 API 的 URL,其中搜索词被引号括起来。例如:
http://www.example.com/searchterm="search".
但是,由于引号的原因,由于 URL 无效,我的 NSURL(由 URLWithString 生成)为 nil。有没有解决的办法?谢谢!
【问题讨论】:
标签: iphone objective-c ios nsurl
我正在使用来自 API 的 URL,其中搜索词被引号括起来。例如:
http://www.example.com/searchterm="search".
但是,由于引号的原因,由于 URL 无效,我的 NSURL(由 URLWithString 生成)为 nil。有没有解决的办法?谢谢!
【问题讨论】:
标签: iphone objective-c ios nsurl
可以在引号前加反斜杠,或者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 是正确的)
尝试以下方法:
#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 不会为零
【讨论】: