在ios 5中建立统一地址搜索栏?

时间:2012-03-12 16:57:04

标签: ios browser address-bar

帮助在ios 5中为浏览器应用程序创建统一地址栏?所以这是我的地址栏。

-(IBAction)url:(id)sender {
    NSString *query = [urlBar.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", query]];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
    [webPage loadRequest:request];
}

我无法添加“其他”引用,如果它不是地址,那么附加谷歌搜索标签?如果是这样的话?你知道怎么用Bing而不是google吗?

-(IBAction)googleSearch:(id)sender {
    NSString *query = [googleSearch.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?hl=en&site=&q=%@", query]];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
    [webPage loadRequest:request];
}

1 个答案:

答案 0 :(得分:0)

以下是一些可以帮助您的提示:

  • 使用stringByAddingPercentEscapesUsingEncoding:代替您的“+”替换。
  • 在添加之前,您应该检查http://是否不是URL字符串的前缀
  • 您应该实施UIWebViewDelegate协议以确定加载无效网址时发生错误的时间
  • 然后作为后备启动你的谷歌搜索(现在你可以用“+”代替“”)......或者Bing,无论你做什么,直到你!

您的代码应如下所示:

...
webView.delegate = self; // Should appear in your code somewhere
...

-(IBAction)performSearch {
    if ([searchBar.text hasPrefix:@"http://"]) {
        ... // Make NSURL from NSString using stringByAddingPercentEscapesUsingEncoding: among other things
        [webView loadRequest:...]
    } else if ([self isProbablyURL:searchBar.text]) {
        ... // Make NSURL from NSString appending http:// and using stringByAddingPercentEscapesUsingEncoding: among other things
        [webView loadRequest:...]
    } else {
        [self performGoogleSearchWithText:searchBar.text]
    }
}

- (BOOL)isProbablyURL:(NSString *)text {
    ... // do something smart and return YES or NO
}

- (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
    [webView loadRequest:...]
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    ... // Notify user
    if (was not already a Google Search) {
        [self performGoogleSearchWithText:searchBar.text]
    }
}