2012-07-09 99 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網址,以確保它是你所期望的!