iOS Universal Links

iOS Universal Links功能簡介

舉個栗子:用戶在手機上通過Safari瀏覽器?查看簡書的某篇文章時,會打開用戶手機上的簡書App并進(jìn)入到這篇文章,從而實現(xiàn)了從瀏覽器到App的無縫鏈接

前提條件

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

  • iOS 9+
  • 要有一個網(wǎng)站,并且支持Https

配置

JSON配置文件

命名為apple-app-site-association的JSON配置文件,放到網(wǎng)站的根目錄,可以通過Https訪問,以簡書為例子http://jianshu.com/apple-app-site-association

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

簡單解釋一下:如果在瀏覽器中訪問的某個簡書頁面的url匹配paths規(guī)則,則嘗試打開Team IDKS7QAPBMXABundle IDcom.jianshu.Hugo的App,并且將url傳遞給App。

iOS App 配置
Domains配置
iOS接收并處理url參數(shù)

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并進(jìn)入到對應(yīng)的頁面;返回false表示處理失敗,會停留在Safari頁面。

參考:iOS 9學(xué)習(xí)系列:打通 iOS 9 的通用鏈接(Universal Links)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容