0

帮助在 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];
}
4

1 回答 1

0

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

  • 使用stringByAddingPercentEscapesUsingEncoding:而不是您的“+”替换。
  • 您应该在添加之前检查 http:// 是否不是 URL 字符串的前缀
  • 您应该实现UIWebViewDelegate协议以识别加载无效 URL 时何时发生错误
  • 然后作为后备启动你的谷歌搜索(现在你可以用“+”替换“”)......或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]
    }
}
于 2012-03-12T17:10:05.797 回答