2012-04-08 44 views
0

除了當我嘗試搜索兩個以上的單詞時,一切似乎都很好。所以,「蘋果」作爲搜索被髮送到谷歌,但「蘋果的東西」只是無法加載。有任何想法嗎?另外,我將google搜索添加到didfailtoload,但返回了didfailtoload循環。我幾乎在iOS xcode 4.3中有一個統一的搜索欄,但只有一個詞?

-(BOOL)textFieldShouldReturn:(UITextField *)textField { 

    webView.delegate = self; 

    if ([urlField.text hasPrefix:@"http://"]) { 

     [webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString:urlField.text]]]; 
     [urlField resignFirstResponder]; 
     return NO; 

    } else if ([self isProbablyURL:urlField.text]) { 

    NSString *query = [urlField.text stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 
    NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", query]]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery]; 
    [webView loadRequest:request]; 
    [urlField resignFirstResponder]; 
    return NO; 

    } else { 

     ([self performGoogleSearchWithText:urlField.text]); 
     [urlField resignFirstResponder]; 
     return YES; 

    } 
} 


- (void)performGoogleSearchWithText:(NSString *)text { 

    // Make a google request from text and mark it as not being "fallbackable" on a google search as it is already a Google Search 
    NSString *query = urlField.text; 
    NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?hl=en&site=&source=hp&q=%@", query]]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery]; 
    [webView loadRequest:request]; 

} 


- (BOOL)isProbablyURL:(NSString *)text { 

    // do something smart and return YES or NO 
    NSString *urlRegEx = 
    @"((\\w)*|(m.)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|(m.)*|([0-9]*)|([-|_])*))+"; 
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:urlField.text]; 
    //return NO; 

} 

回答

0

-performGoogleSearchWithText:您正在創建一個Google URL,其中包含用戶提供的搜索字符串。但是,如果查詢包含多個單詞,則單詞之間會有空格,NSURL將拒絕創建URL,因爲它將包含無效字符。爲了達到這個目的,你必須用百分比轉義等價物替換空格字符,例如%20。

在以下版本的-performGoogleSearchWithText:方法中,我使用NSStrings +stringByAddingPercentEscapesUsingEncoding:方法將URL中無效的字符替換爲URL百分比編碼的等效字符。

- (void)performGoogleSearchWithText:(NSString *)text { 
    // Make a google request from text and mark it as not being "fallbackable" on a google search as it is already a Google Search 
    NSString *query = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?hl=en&site=&source=hp&q=%@", query]]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery]; 
    [webView loadRequest:request]; 
} 

注:我用文字傳入的參數,而不是讓用戶直接使用urlField.text用戶界面查詢。

+0

工程很好。你救了我的大腦。謝謝! – user1264599 2012-04-08 17:21:08

相關問題