在iOS 7中创建通用搜索文本字段(google和url)

时间:2013-10-01 04:42:50

标签: ios safari

我们如何创建iOS 7 Safari中的通用搜索文本字段。我知道如何创建Google搜索字段,但如何创建一个同时包含Google搜索和网址搜索的文本字段。

Google搜索字段:

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

3 个答案:

答案 0 :(得分:4)

Google Chrome假设在这些情况下输入的文字是网址:

  1. 文字不包含空格(一个单词):
    1. 以有效且已接受的URI scheme开头(例如httphttpsftp
    2. 以正斜杠(/)开始。
    3. 以有效TLD结束(请参阅123)。
    4. 以正斜杠结束(/)。
    5. 已知主机名(如localhost)。
    6. 有效IP addresses
  2. 文字包含空格(多个单词):
    1. 以正斜杠(/)开始。
  3. 文字包含问号(?),可以假定其前面的部分为网址。
  4. 在所有其他情况下,您可以放心地假设键入的文本是搜索词。

    这不是完整的规则列表,但我认为这对于常规使用来说已经足够了。

    主要参考:Chromium - Omnibox design principles

    <强> 更新

    以下是一些提示,可帮助您将之前的规则转换为有效的代码(顺序很重要):

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

      \?.*$
      

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

    • 规则1.1 1.2 1.4 1.5 2.1 < / strong>)匹配此正则表达式:

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

      \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])$
      

答案 1 :(得分:2)

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

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

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

答案 2 :(得分: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;
}