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 ID
為KS7QAPBMXA
且Bundle ID
為com.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頁面。