3

我们如何像在 iOS 7 Safari 中一样创建通用搜索文本字段。我知道如何创建 Google 搜索字段,但如何创建一个同时具有 Google 搜索和 URL 搜索的文本字段。

谷歌搜索域:

    -(void)SearchButtonClicked {

        NSString *query = [maintext.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
        NSString *urlString = [NSString stringWithFormat:@"%@", query];

        // remember to change the view controller class in storyboard
        MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebView"];

        // urlString is a public property on MyWebViewController
        webViewController.urlString = urlString;
        [self presentViewController:webViewController animated:YES completion:nil];  
    }

    - (IBAction)SearchButton:(id)sender {

        NSString *query = [maintext.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
        NSString *urlString = [NSString stringWithFormat:@"http://www.google.com/search?q=%@", query];

        // remember to change the view controller class in storyboard
        MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebView"];

        // urlString is a public property on MyWebViewController
        webViewController.urlString = urlString;
        [self presentViewController:webViewController animated:YES completion:nil];
}

我的 Webview 控制器:

#import "MyWebViewController.h"
#import "ViewController.h"
#import <Social/Social.h>
#import "SIAlertView.h"
#import "TTAlertView.h"

#import "ETActivityIndicatorView.h"



@implementation MyWebViewController {


}

@synthesize searchField;

@synthesize webView;

ETActivityIndicatorView * etActivity;

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    NSURL *url = [NSURL URLWithString:self.urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];



}

-(void)webView:(UIWebView *)webBlog didFailLoadWithError:(NSError *)error{

    if ([error code] != -999) {
        NSLog(@"Could not load the dumb webPage");
        //show error alert, etc.

        TTAlertView *alert = [[TTAlertView alloc] initWithTitle:@"Internet Error"
                                                        message:@"Searched cannot open the page because your iPhone is not connected to the internet."
                                                       delegate:self
                                              cancelButtonTitle:@"Dismiss"
                                              otherButtonTitles:nil];

        [alert show];

        [etActivity setHidden:YES];


    }else{

        NSLog(@"Could not load the dumb web page...just might blame user!");
    }
}


//Called whenever the view starts loading something
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [etActivity startAnimating];

    [etActivity setHidden:NO];
}

//Called whenever the view finished loading something
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [etActivity stopAnimating];

    [etActivity setHidden:YES];

}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [webView setDelegate:self];

    self.searchField.backgroundColor = [UIColor colorWithRed:255.0/255 green:255.0/255 blue:255.0/255 alpha:1.0f];
    self.searchField.layer.cornerRadius = 3.0f;
    self.searchField.placeholder = @"Search or enter address";
    self.searchField.leftViewMode = UITextFieldViewModeAlways;
    UIView* leftView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    self.searchField.leftView = leftView1;

    //Setup handling of LEFT and RIGHT swipes
    UISwipeGestureRecognizer *recognizer;

    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];


    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];

    self.searchField.delegate = self;

    //ETActivityIndicatorView
    etActivity = [[ETActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 60.0f, 60.0f)];

    etActivity.center=self.view.center;

    //you can set your custom color for ETActivityIndicatorView
    etActivity.color = [UIColor colorWithRed:13.0/255 green:136.0/255 blue:236.0/255 alpha:1.0f];

    [self.view addSubview:etActivity];
}


-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {

    if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        NSLog(@"Swipe Right");
          [webView goBack];
    }

    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        NSLog(@"Swipe Left");
         [webView goForward];
    }

}


#pragma mark - RNGridMenuDelegate
- (void)gridMenu:(RNGridMenu *)gridMenu willDismissWithSelectedItem:(RNGridMenuItem *)item atIndex:(NSInteger)itemIndex {

    if (itemIndex == 0) {
        NSLog(@"Reload");

        [self.webView reload];
    }

    if (itemIndex == 1) {
        NSLog(@"Facebook");

        if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) //check if Facebook Account is linked
        {
            mySLComposerSheet = [[SLComposeViewController alloc] init]; //initiate the Social Controller
            mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; //Tell him with what social plattform to use it, e.g. facebook or twitter
            [mySLComposerSheet setInitialText:[NSString stringWithFormat:@""]]; //the message you want to post

                       [self presentViewController:mySLComposerSheet animated:YES completion:nil];
        }
        [mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {

            switch (result) {
                case SLComposeViewControllerResultCancelled:

                    break;
                case SLComposeViewControllerResultDone:

                    break;
                default:
                    break;
            } //check if everything worked properly. Give out a message on the state.

        }];



    }
    if (itemIndex == 2) {

        if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
        {
            SLComposeViewController *tweetSheet = [SLComposeViewController
                                                   composeViewControllerForServiceType:SLServiceTypeTwitter];
            [tweetSheet setInitialText:@""];
            [self presentViewController:tweetSheet animated:YES completion:nil];
        }

    }

    if (itemIndex == 3) {
        NSLog(@"Home");

        MyWebViewController *MainView = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"];
        [self presentViewController:MainView animated:NO completion:nil];

    }

}




- (void)showList {
    NSInteger numberOfOptions = 4;
    NSArray *options = @[
                         @"Reload",
                         @"Facebook",
                         @"Twitter",
                         @"Home",

                         ];
    RNGridMenu *av = [[RNGridMenu alloc] initWithTitles:[options subarrayWithRange:NSMakeRange(0, numberOfOptions)]];
    av.delegate = self;
    av.itemFont = [UIFont boldSystemFontOfSize:18];
    av.itemSize = CGSizeMake(150, 55);
    [av showInViewController:self center:CGPointMake(self.view.bounds.size.width/2.f, self.view.bounds.size.height/2.f)];
}


- (IBAction)onShowButton:(id)sender {
    [self showList];
}


![enter image description here][1]
4

3 回答 3

4

在以下情况下,Google Chrome 会假定输入的文本是 URL:

  1. 文本不包含空格(一个单词):
    1. 以有效且可接受的URI 方案(如httphttpsftp)开头。
    2. 以正斜杠 ( /) 开头。
    3. 以有效的TLD结尾(请参阅123)。
    4. 以正斜杠 ( /) 结尾。
    5. 已知主机名(Like localhost)。
    6. 有效的IP 地址
  2. 文本包含空格(多个单词):
    1. 以正斜杠 ( /) 开头。
  3. 文本包含一个问号 ( ?) 和可以假定为 URL 的部分。

在所有其他情况下,您可以放心地假设输入的文本是搜索词。

这不是一个完整的规则列表,但我认为对于常规使用来说已经绰绰有余了。

主要参考:Chromium - Omnibox 设计原则

更新:

这里有一些提示可以帮助您将之前的规则转换为工作代码(顺序很重要):

  • 规则3)替换匹配这个正则表达式的部分文本:

    \?.*$
    

    使用空字符串@"",然后应用其他规则。

  • 规则 1.11.21.41.52.1)匹配这个正则表达式:

    ^((\/)|((https?|ftp):\S+$)|(\S+\/$)|(localhost$))
    
  • 规则 1.3)您可以从上面的链接中收集一些流行的 TLD,并从中形成一个正则表达式,如下所示:

    \S+\.(com|net|org|....)$
    
  • 规则 1.6)匹配这个正则表达式:

    ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9‌​]{2}|2[0-4][0-9]|25[0-5])$
    
于 2013-10-11T00:32:50.403 回答
2

使用此代码。这基本上检查输入到文本字段中的文本。如果它是一个完整的 url,那么它会直接重定向到它,否则在谷歌上搜索输入的文本。

- (IBAction)SearchButton:(id)sender 
{
    MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebView"];

    NSString *urlString = maintext.text;
    if([urlString rangeOfString:@"//"].location == NSNotFound)
    {
        // to resolve a url according to rfc 1808 (the most common form of URL), it must contain '//' in it.
        // appending '//' in the url string to check for valid url
        urlString = [NSString stringWithFormat:@"//%@", urlString];
    }

    NSURL *url = [NSURL URLWithString:urlString];
    if(url && (url.scheme || url.host) && ([urlString rangeOfString:@"."].location != NSNotFound))
    {
       // url is valid, it contains domain and host
        webViewController.urlString = maintext.text;
    }
    else 
    {
        NSString *query = [maintext.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
        NSString *urlString = [NSString stringWithFormat:@"http://www.google.com/search?q=%@", query];

        // urlString is a public property on MyWebViewController
        webViewController.urlString = urlString;
    }

    [self presentViewController:webViewController animated:YES completion:nil];
}

对于额外的检查,您还可以检查 url 是否有效,例如 ping 并检查它是否响应。

于 2013-10-01T07:35:02.863 回答
0

您可以创建一个类别:

@interface NSString (NSStringValidator)
- (BOOL)isValidEmail;
- (BOOL)isValidURL;
@end

@implementation NSString (NSStringValidator)
- (BOOL)isValidEmail {
    NSString *regExpPattern = @"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b";

    NSError *errorNext = NULL;
    NSRegularExpression *regexNext = [NSRegularExpression regularExpressionWithPattern:regExpPattern
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&errorNext];
    NSRange range = [regexNext rangeOfFirstMatchInString:self
                                                 options:NSRegularExpressionCaseInsensitive
                                                   range:NSMakeRange(0, self.length)];
    return NSEqualRanges(range, NSMakeRange(0, self.length));
}

- (BOOL)isValidURL {
    NSString *regExpPattern = @"(?i)(?:(?:https?):\\/\\/)?(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?";

    NSError *errorNext = NULL;
    NSRegularExpression *regexNext = [NSRegularExpression regularExpressionWithPattern:regExpPattern
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&errorNext];
    NSRange range = [regexNext rangeOfFirstMatchInString:self
                                                 options:NSRegularExpressionCaseInsensitive
                                                   range:NSMakeRange(0, self.length)];
    return NSEqualRanges(range, NSMakeRange(0, self.length));
}
@end

然后调用分类方法:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
    [theTextField resignFirstResponder];

    if (theTextField.text.isValidURL) {
        //open site
    } else {
        //search text
    }

    return YES;
}
于 2013-12-03T12:40:49.553 回答