向浏览器添加内置的Google搜索功能

时间:2015-07-03 23:02:36

标签: ios objective-c iphone

我试图让我的简单浏览器能够识别带空格的文本应该被视为谷歌搜索查询。要创建一个可以进入url的字符串,我需要用“+”s替换空格。

我试图在第一个“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;

}

1 个答案:

答案 0 :(得分:0)

我认为您可能遇到第3个条件发出第2个请求的问题。如果你改成它怎么办?

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