iOS Universal Links

iOS Universal Links功能简介

举个栗子:用户在手机上通过Safari浏览器�查看的某篇文章时,会打开用户手机上的App并进入到这篇文章,从而实现了从浏览器到App的无缝链接

前提条件

要使用iOS Universal Links功能需要如下前提条件:

  • iOS 9+
  • 要有一个网站,并且支持Https

配置

JSON配置文件

命名为apple-app-site-association的JSON配置文件,放到网站的根目录,可以通过Https访问,以为例子http://jianshu.com/apple-app-site-association

{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "KS7QAPBMXA.com.jianshu.Hugo",
        "paths": [ "/p/*", "/collection/*", "/users/*", "/notebooks/*" ]
      }
    ]
  }
}

简单解释一下:如果在浏览器中访问的某个页面的url匹配paths规则,则尝试打开Team IDKS7QAPBMXABundle IDcom.jianshu.Hugo的App,并且将url传递给App。

iOS App 配置
iOS Universal Links_第1张图片
Domains配置
iOS接收并处理url参数

AppDelegate

import UIKit
 
extension AppDelegate {
    func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
        if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
            let webpageURL = userActivity.webpageURL! // Always exists
            if !handleUniversalLink(URL: webpageURL) {
                UIApplication.sharedApplication().openURL(webpageURL)
            }
        }
        return true
    }
     
    private func handleUniversalLink(URL url: NSURL) -> Bool {
        if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: true), let host = components.host, let pathComponents = components.path?.pathComponents {
            switch host {
            case "domain.com":
                if pathComponents.count >= 4 {
                    switch (pathComponents[0], pathComponents[1], pathComponents[2], pathComponents[3]) {
                    case ("/", "path", "to", let something):
                        if validateSomething(something) {
                            presentSomethingViewController(something)
                            return true
                        }
                    default:
                        return false
                    }
                }
            default:
                return false
            }
             
        }
        return false
    }
}

返回true表示处理成功,会打开App并进入到对应的页面;返回false表示处理失败,会停留在Safari页面。

参考:iOS 9学习系列:打通 iOS 9 的通用链接(Universal Links)

你可能感兴趣的:(iOS Universal Links)