iOS 通用链接Universal Link
是在'URL Scheme'实现跳转外的另外一种跳转方式,不同于URL Scheme
,Universal Link
可以不经过Safari
而直接跳转到你的App中(如果App没有安装,则在Safari中打开website)。
苹果文档Support Universal Links指出Universal Link
相对于Custom URL Scheme
有很多好处:
Unique: 无法被其他app声明,因为使用的是指向你自己website的链接
Secure: 当app被安装时,iOS会检查你上传到web server的文件,以此来验证app是否可以打开链接
Flexible: 即使app没有安装的情况下,打开链接也可以在safari上显示内容
Simple: 同样的URL同时应用于website和app
Private: 在不知道你的app是否安装的情况下,其他app也可以与你的app通信
根据文档,我们仅需三步,就可以支持Universal Link
:
第一步
Create an apple-app-site-association file that contains JSON data about the URLs that your app can handle.
apple-app-site-association
文件,文件名无后缀:
{
"applinks": {
"apps": [],
"details": [
{
"appID": "9JA89QQLNQ.com.apple.wwdc",
"paths": [ "/wwdc/news/", "/videos/wwdc/2015/*"]
},
{
"appID": "ABCD1234.com.apple.wwdc",
"paths": [ "*" ]
}
]
}
}
其中,apps
必为空,appID
即是你的App的bundle id
,paths
即是app与website关联的链接路径,也可以加NOT
直出不需要关联的路径:
"paths": [ "/wwdc/news/", "NOT /videos/wwdc/2010/*", "/videos/wwdc/201?/*"]
第二步
Upload the apple-app-site-association file to your HTTPS web server. You can place the file at the root of your server or in the .well-known subdirectory.
将apple-app-site-association
文件上传到HTTPS的根目录,或者.well-known
子目录,以便可以直接通过如下链接访问:
https://<domain>/apple-app-site-association
https://<domain>/.well-known/apple-app-site-association.
第三步
Prepare your app to handle universal links.
在苹果开发者网站打开Associated Domains
功能:
在XCode的配置中,打开Associated Domains
功能:
添加以applinks
开头的域名:
会自动生成含有这个域名的Entitlements.plist
文件:
最后就是要在ApplicationDelegate
中实现处理函数:
// Called on the main thread as soon as the user indicates they want to continue an activity in your application. The NSUserActivity object may not be available instantly,
// so use this as an opportunity to show the user that an activity will be continued shortly.
// For each application:willContinueUserActivityWithType: invocation, you are guaranteed to get exactly one invocation of application:continueUserActivity: on success,
// or application:didFailToContinueUserActivityWithType:error: if an error was encountered.
@available(iOS 8.0, *)
optional public func application(_ application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool
// If the user activity cannot be fetched after willContinueUserActivityWithType is called, this will be called on the main thread when implemented.
@available(iOS 8.0, *)
optional public func application(_ application: UIApplication, didFailToContinueUserActivityWithType userActivityType: String, error: Error)