在谷歌搜索

时间:2012-02-20 19:04:09

标签: iphone objective-c ios ipad

所以我创建了一个文本字段,可以搜索网络或Google。问题是我无法在谷歌上搜索多个单词:我可以搜索Stackoverflow,但我无法搜索Stackoverflow问题,例如。这是代码:

{

if ([textField.text hasPrefix:@"http"]){
    url=[NSURL URLWithString:[textField text]];
    request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    }else{
        stringOne = @"http://www.google.com/search?q=";
        NSString *stringTwo = TextField.text;
        NSString *googleSearchString =[stringOne stringByAppendingString:stringTwo];
        NSURL *google =  [NSURL URLWithString:googleSearchString ];
        request = [NSURLRequest requestWithURL:google ];
        [webView loadRequest:request];
    }
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

您的字符串可能无法正确编码。也许试试:

NSString* newGoogleSearchString = 
          [googleSearchString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

答案 1 :(得分:2)

如果您在浏览器中查看网址,您会看到以下内容:

http://www.google.com/search?client=safari&rls=en&q=Stackoverflow+questions&ie=UTF-8&oe=UTF-8

重要的论点是& q = Stackoverflow +问题,请注意代表空格的'+'符号。

因此,如果您希望代码正常工作,则必须使用“+”字符替换空格。