2015-07-03 104 views
0

我想讓我的簡單瀏覽器能夠識別帶空格的文本,並將其視爲Google搜索查詢。要創建一個可以進入url的字符串,我需要用「+」替換空格。在瀏覽器中添加內置Google搜索功能

我曾嘗試在第一個「if」語句中執行此操作,但是當我運行該程序並將帶有空格的文本放入搜索欄時什麼也沒有發生;輸入「google.com」或其他網址雖然工作。

我的代碼有什麼問題?

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    [textField resignFirstResponder]; 

    NSString *URLString = textField.text; 

    NSURL *URL = [NSURL URLWithString:URLString]; 

    if ([URLString rangeOfString:@" "].location != NSNotFound) { 
    NSString *plusReplace = [URLString stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 
    URL = [NSURL URLWithString:[NSString stringWithFormat:@"google.com/search?q=<%@ query", plusReplace]]; 


    } 

    if (!URL.scheme) { 
     // The user didn't type http: or https: 
     URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", URLString]]; 
    } 

    if (URL) { 
     NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
     [self.webView loadRequest:request]; 

    } 

    return NO; 

} 

回答

0

我想你可能會遇到第三個有問題的請求。如果你改變它呢?

if (URL) { 
    NSString *plusReplace = [URLString stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 
    URL = [NSURL URLWithString:[NSString stringWithFormat:@"google.com/search?q=<%@ query", plusReplace]]; 
} 

if (!URL.scheme) { 
    // The user didn't type http: or https: 
    URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", URLString]]; 
} 

NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
[self.webView loadRequest:request]; 
+0

功能仍然不能與您所做的更改一起工作,謝謝指出雙重條件。 –

+0

當提交空格時,你是否有辦法計算出正在請求的內容?如果我正在調試這件事,那將是我首先要檢查的事情。 –

+0

我不知道當提交空格時程序會做什麼,我必須找出答案。 –