2012-07-09 102 views
1

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

例:替换行{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

您可以创建自己的URL字符串并将它们传递给UIWebView! – trumpetlicks 2012-07-09 14:51:15

+0

我认为在你调用NSURLRequest的时候,缺少转换为NSURL类型的问题。看看我的答案! – trumpetlicks 2012-07-09 15:41:45

回答

3

像这样的事情?

NSString *request = [NSString stringWithFormat:@"http://stackoverflow.com/search?q=%@&submit=search", @"USER ENTRY"]; 
+0

从字符串的角度来看,我认为这是最好的答案,因为它需要更少的实际NSString分配。 – trumpetlicks 2012-07-09 15:43:19

1

的NSString给你的方法stringByReplacingOccurrencesOfString:withString:,您可以使用:

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

的NSMutableString具有用于就地修改字符串类似的方法。

注意:“发生”中有两个r - 我最初拼写错误。这是你得到的错误的来源 - 你必须正确拼写方法名称。

+0

这是我的代码到目前为止它给我的错误:'NSString'没有可见的@interface声明选择器''stringByReplacingOccurencesOfString:withString:' – atomikpanda 2012-07-09 15:19:55

+0

我更新了我的帖子。 – atomikpanda 2012-07-09 15:28:09

+1

请参阅我添加的说明。您必须正确拼写方法名称。 – Caleb 2012-07-09 15:37:19

0

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

尝试:

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

你也可以尝试,而不是替代的字符串创建也luxsypher的回答。

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