【iOS】Universal Link 实施步骤

547 阅读3分钟

Universal Link 实施步骤

当我们使用URL scheme 从web网页启动APP时,如果APP未安装,会提示出错,打断用户操作,从APP使用URL Scheme跳转另一个APP时如果该APP没有安装,也会跳转失败。

如果APP支持Universal Link,就可以实现APP和web网页间的顺滑衔接。也可实现APP间的跳转,不再依赖URL Scheme。

当从Web网页打开支持Universal Link的链接时,如果有安装相应APP,则会直接跳转到APP继续操作,如果没有安装,也能正常的打开网页链接,不会报错。

当从APP使用UIApplication.shared.open()方法打开一个支持Universal Link 的URL时也是同样的,如果安装了支持该Universal Link的APP则直接启动APP,如果没有安装,则会打开相应的网页。大大的改善了用户体验。

服务器配置

  • 需要一个支持 HTTPS 的域名

  • apple-app-site-association上传到该域名的根目录或.well-known目录中

    确保文件可以直接通过 https://xxxx.com/apple-app-site-associationhttps://xxxx.com/.well-known/apple-app-site-association 直接访问,其中 xxxx.com 为自己的域名。iOS 会在APP安装时请求这个文件来查询APP的Universal Link配置。

  • apple-app-site-association的内容为Json,Apple官方文档:Supporting Associated Domains | Apple Developer Documentation,示例如下

    {
        "applinks": {
            "details": [
                {
                    "appID": "9JA89QQLNQ.com.apple.wwdc",
                    "paths": [ "/wwdc/news/", "/videos/wwdc/2015/*"]
                },
                {
                    "appID": "ABCD1234.com.apple.wwdc",
                    "paths": [ "*" ]
                }
            ]
        }
    }
    

    其中:

    • details 中包含了支持Universal Link的App 的信息,可以是一个或多个
      • appIDTeamID.BundleID,例如:9JA89QQLNQ.com.apple.wwdc,其中9JA89QQLNQTeam IDcom.apple.wwdc为Bundle ID
      • paths 为支持 Universal Link 的URL Path,支持通配符 *。

    TeamID 可在Developer Account 的 Membership 中查看

image-20201129214401179.png

Apple账号配置

  • 在 Apple Developer 账号的 “Certificates, Identifiers & Profiles” - “Identifiers” APP ID 对应的菜单中打开 “Associated Domains” 选项

image-20201129211002922.png

Xcode工程配置

  • targets > Capabilites > Associated DomainsDomains中填入你想支持的域名,必须以applinks:为前缀

image-20201129213934410.png

使用Universal Link

  • web端

    只需要使用常规的 <a>标签即可。

  • iOS原生端

    使用 UIApplication.shared.open()方法打开支持Universal Link的URL即可。

Universal Link注意点

  1. Universal Link跨域

    当在web网页使用Universal Link时有跨域问题,Universal Link 必须要求跨域,如果不跨域,就不会跳转(iOS 9.2之后的改动) 。假如当前网页的域名是A,当前网页发起跳转的域名是B,必须要求BA是不同域名才会触发Universal Link,如果BA是相同域名,只会继续在当前WebView里面进行跳转,哪怕你的Universal Link一切正常,根本不会打开App

  2. iOS 系统请求apple-app-site-association配置文件的时机

    • 当我们的App在设备上第一次运行时,如果APP支持Associated Domains功能,那么iOS会自动通过GET方式请求定义在Xcode工程配置 Domains 域名下的 apple-app-site-association 文件

    • iOS会先请求https://xxx.com/.well-known/apple-app-site-association,如果此文件请求不到,再去请求根目录https://xxx.com/apple-app-site-association,所以如果想要避免服务器接收过多GET请求,可以直接把apple-app-site-association放在./well-known目录下

    • 服务器上apple-app-site-association的更新不会让iOS本地的apple-app-site-association同步更新,即iOS只会在App第一次启动时请求一次,以后除非App更新或重新安装,否则不会在每次打开时请求apple-app-site-association