美文网首页
跳转到浏览器中后, 使用百度搜索指定字符串

跳转到浏览器中后, 使用百度搜索指定字符串

作者: 伯wen | 来源:发表于2016-11-12 18:26 被阅读870次

    <p>有时, 我们需要在外部浏览器中打开百度界面, 并直接搜索某一段字符串, 我们可以通过下面的代码来完成这个需求

    • 效果图:
    效果图.gif
    • 输入框中输入内容后, 通过点击View直接跳转Safari, 然后使用百度直接搜索指定字符串
    #import "ViewController.h"
    
    @interface ViewController ()
    
    /** 输入框 */
    @property (nonatomic, strong) UITextField *textField;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 200, 40)];
        self.textField.borderStyle = UITextBorderStyleRoundedRect;
        [self.view addSubview:self.textField];
        
    }
    
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        // 没有内容直接返回
        if (self.textField.text.length == 0) return;
        
        // 需要搜索的内容
        NSString * keyword = self.textField.text;
    
        //适配 iOS9 字符串UTF8编码
        if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_9_0) {
             keyword = [keyword stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }else {
            keyword = [keyword stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    
        // 拼接链接字符传
        NSString * urlStart = @"https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=";
        NSString * urlEnd = @"&rsv_pq=80c7023000194588&rsv_t=e923%2BJi6SI0Q7Kl1q1%2BUl%2Bq7jbwN0GzkIghhykTbOJO0WX2%2BnR6iKTwQWLI&rsv_enter=1&inputT=7275&rsv_sug3=20&rsv_sug1=19&rsv_sug2=0&rsv_sug4=7642";
        NSMutableString * urlStr = [[NSMutableString alloc]init];
        [urlStr appendString:urlStart];
        [urlStr appendString:keyword];
        [urlStr appendString:urlEnd];
    
    
        NSURL * url = [NSURL URLWithString:[NSString stringWithString:urlStr]];
    
        //适配 iOS10 跳转Safari浏览器
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_x_Max) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            }else {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:跳转到浏览器中后, 使用百度搜索指定字符串

          本文链接:https://www.haomeiwen.com/subject/izuqpttx.html