1

我想使用 UIWebView 在 iPhone 中创建自定义搜索。

示例:将{query}下面一行中的内容替换为用户输入的内容。

网址: http://stackoverflow.com/search?q={query}&submit=search

最终代码:

[super viewDidLoad];
_webView.delegate = self;
NSString *queryString = _searchField.text;
NSString *request2 = [NSString stringWithFormat:@"http://stackoverflow.com/search?q=%@&submit=search", queryString];
NSURLRequest *requestURL = [NSURLRequest requestWithURL:[NSURL URLWithString:request2]];

[_webView setScalesPageToFit:YES];
[self.webView loadRequest:requestURL];
4

3 回答 3

3

像这样的东西?

NSString *request = [NSString stringWithFormat:@"http://stackoverflow.com/search?q=%@&submit=search", @"USER ENTRY"];
于 2012-07-09T14:54:02.107 回答
1

NSString 为您提供了stringByReplacingOccurrencesOfString:withString:可以使用的方法:

NSString *request = [urlString stringByReplacingOccurrencesOfString:@"{query}"
                                                        withString:queryString];

NSMutableString 有类似的方法来修改字符串。

注意: “Occurrences”中有两个 r——我最初拼错了。这是您得到的错误的根源——您必须正确拼写方法名称。

于 2012-07-09T14:58:35.863 回答
0

在将字符串发送到您的 NSURLRequest“请求”之前,您似乎没有将其转换为 URL 对象类型。

尝试:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:request2]];

您也可以尝试 luxsypher 的字符串创建答案,而不是替换。

此外,您可能会考虑打印出您的 NSString 网址,以确保它是您所期望的!

于 2012-07-09T15:30:35.563 回答