iOS url schemes应用

url schemes在iOS开发中的应用场景分别是应用间跳转、UIWebView与JavaScript交互。

一.应用间跳转

设置应用间跳转的步骤:
自家app->info->url types 中添加微信的url schemes,并且要在自家app.plist文件支持跳转白名单中加入微信的url schemes。
假设微信的url schemes为weixin,identifier为com.wx.test。
则自家app的跳转代码为如下:

NSString *str = @"weixin://com.wx.test?viewId=letters";
    NSURL *url = [NSURL URLWithString:str];
    if ([[UIApplication sharedApplication] canOpenURL:url])
    {
        [[UIApplication sharedApplication] openURL:url];
    }

同理,从微信中跳转回自家app,微信也需要获得自家app的url schemes,白名单中拥有自家app的url schemes。

 二.UIWebView与JavaScript交互

UIWebView调用JavaScript中的hellowWorld函数

[self.webView stringByEvaluatingJavaScriptFromString:@"helloWorld('从ios对象中调用JS helloWorld(msg)函数')"];

index.html

<!DOCTYPE html>
<html>
    <body>
        
        <button onclick='showAndroidDialog("JS 调用IOS 对象")'>click</button>
        </br>
        <div id = 'message'></div>
        
        
        <script>
            function helloWorld(msg)
            {
                document.getElementById('message').innerHTML = msg;
            }
        
        function showAndroidDialog(msg)
        {
            var myJsonObject = new Object();
            myJsonObject.title = 'forr';
            myJsonObject.message = msg;/*JS 调用IOS 对象*/
            
            /*通用对象标识uri
             **<scheme>       gap
             **<host>         XXXClass.XXXMethod
             **[?<query>]
             **[#<fragment>]  {"title":"forr","message":"JS 调用IOS 对象"}
             */
            var JsonString = JSON.stringify(myJsonObject);
            var uri = 'gap://XXXClass.XXXMethod#'+JsonString;
            window.location = uri;//重定向url
        }
        </script>
        
    </body>
</html>
在UIWebView的代理方法中去拦截自定义的协议gap:,如果是此协议则据此判断JavaScript想要做的事情,调用原生应用的方法,这些都是提前约定好的,同时阻止此链接的跳转。
-(BOOL)webView:(UIWebView *)webView
    shouldStartLoadWithRequest:(NSURLRequest *)request
    navigationType:(UIWebViewNavigationType)navigationType
{
    //获取js信息
    NSString *actionType = request.URL.host;
    NSString *scheme = request.URL.scheme;
    
    
    NSString *fragment = [request.URL.fragment URLDecodedString];//url解码
    NSData *responseData = [fragment dataUsingEncoding:NSUTF8StringEncoding];
    if ([scheme isEqualToString:@"gap"])
    {
        if ([actionType isEqualToString:@"XXXClass.XXXMethod"])
        {
            NSError *error;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
            NSLog(@"title = %@,message = %@",[json objectForKey:@"title"],[json objectForKey:@"message"]);
        }
     return NO; }
return YES; }

 

 

 

 

 

posted @ 2016-03-08 15:43  forrHuen  阅读(590)  评论(0编辑  收藏  举报