0

除非我尝试搜索两个以上的单词,否则一切似乎都运行良好。因此,“apple”作为搜索被发送到谷歌,但“apple stuff”无法加载。有任何想法吗?此外,我将谷歌搜索添加到 didfailtoload 中,但返回了一个 didfailtoload 循环。

-(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;

}
4

1 回答 1

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.

于 2012-04-08T14:18:33.340 回答