返回 导航

Swift

hangge.com

Swift - URL schemes的使用样例(如:在Safari中打开App)

作者:hangge | 2016-02-19 08:53
(本文代码已升级至Swift4)

一、基本介绍

1,URL scheme 的作用

我们可以将应用“绑定”到一个自定义 URL scheme 上,该 scheme 用于从浏览器或其他应用中启动本应用,同时跳转时也可以传递参数。
下面通过样例演示 URL schemes 的使用。
 

2,URL scheme 的配置

(1)在“项目” -> “info” -> “URL Types”中,新增一个URL Schemes

(2)其实只要通过上面的配置就可以打开应用了。但有时我们还要传递参数进来,然后程序根据参数调用不同的功能或打开不同的页面。
我们可在 AppDelegate.swift 中的如下方法里获取参数,并做相应的处理。这里直接将参数打印出来:
func application(_ app: UIApplication, open url: URL,
                 options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    if url.host == nil {
        return true;
    }
    
    //获取来源应用的Identifier
    print("来源App:\(options[UIApplicationOpenURLOptionsKey.sourceApplication]!)")
    
    //获取url以及参数
    let urlString = url.absoluteString
    let queryArray = urlString.components(separatedBy: "/")
    print(urlString)
    
    let alertController = UIAlertController(title: "参数如下",
                                            message: "\(queryArray[2])  \(queryArray[3])",
        preferredStyle: .alert)
    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
    alertController.addAction(cancelAction)
    self.window!.rootViewController!.present(alertController, animated: true,
                                             completion: nil)
    
    return true
}

二、从Safari中打开并跳转到这个App

1,跳转的实现

假设我们有如下的html页面:
<html>
<title>Deep Link测试</title>
<meta name="viewport" content="width=device-width,
 initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<body>
    <a href="hangge://article/A">hangge://article/A</a>
    <P>
    <a href="hangge://article/B">hangge://article/B</a>
    <P>
    <a href="hangge://article/C">hangge://article/C</a>
    <P>
</body>
</html>
使用 Safari 打开这个页面,点击链接。可以看到跳转成功了。
            

2,跳转前判断设备是否有这个App

下面通过 js 来进行跳转,这样当手机未安装该应用时,浏览器也会进行提示并跳转到 App Store 去下载。
<html>
<title>Deep Link测试</title>
<meta name="viewport" content="width=device-width,
 initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<script type="text/javascript">
	function startMyApp(url)
	{
	  document.location = url;
	  setTimeout( function()
	  {
		  if( confirm( '您还未安装这个应用,是否现在去AppStore下载该应用?'))
		  {
			document.location = 'https://itunes.apple.com/cn/app/qq-you-xiang/id473225145?mt=8';
		  }
	  }, 500);
	 }
</script>
<body>
	<a href="#" onclick="startMyApp('hangge://article/A')">hangge://article/A</a>
	<P>
	<a href="#" onclick="startMyApp('hangge://article/B')">hangge://article/B</a>
	<P>
	<a href="#" onclick="startMyApp('hangge://article/C')">hangge://article/C</a>
	<P>
</body>
</html>

三、从另一个APP中打开并跳转到这个App

1,跳转的实现

我们另外创建一个新的应用,在页面上添加一个跳转按钮,点击后通过 openURL 方法就可以打开前面那个APP。

(1)由于iOS9的安全策略的改变,如果直接通过openURL打开APP的话,会出现如下错误:
canOpenURL: failed for URL: "hangge://article/C" - error: "This app is not allowed to query for scheme hangge"
我们需要去 Info.plist 里面建立一个叫 LSApplicationQueriesSchemes Array,把允许的 URL Scheme 添加进去:
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>hangge</string>
</array>

(2)跳转代码
import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button:UIButton = UIButton(type:.system)
        button.frame = CGRect(x:10, y:150, width:150, height:30)
        button.setTitle("打开另一个APP", for:.normal)
        button.addTarget(self, action:#selector(ViewController.tapped), for:.touchUpInside)
        self.view.addSubview(button);
    }
    
    @objc func tapped(){
        let urlString = "hangge://article/C"
        let url = URL(string: urlString)
        UIApplication.shared.open(url!)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

(3)点击按钮,可以看到跳转成功了。
            

2,跳转前判断设备是否有这个App

(1)如果是从另一个 App 跳转过来的话,我们可以先使用 canOpenURL() 方法判断应用是否已在本机安装,没有的话打开对应的 App Store 页面。
import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button:UIButton = UIButton(type:.system)
        button.frame = CGRect(x:10, y:150, width:150, height:30)
        button.setTitle("打开另一个APP", for: .normal)
        button.addTarget(self,action:#selector(ViewController.tapped),for:.touchUpInside)
        self.view.addSubview(button);
    }
    
    @objc func tapped(){
        let urlString = "hangge://article/C"
        let url = URL(string: urlString)
        if UIApplication.shared.canOpenURL(url!) {
            UIApplication.shared.open(url!)
        }else{
            let appString = "https://itunes.apple.com/cn/app/qq-you-xiang/id473225145?mt=8"
            let appUrl = URL(string: appString)
            UIApplication.shared.open(appUrl!)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

(2)同时由于 iOS 9 系统策略更新,限制了 http 协议的访问。我们还需在“Info.plist”(发起跳转的那个应用)中将要使用的 URL Schemes 列为白名单,才可正常检查其他应用是否安装。
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>hangge</string>
</array>
评论

全部评论(4)

回到顶部