URL Scheme

2020-02-26  本文已影响0人  oncezou

URL Scheme: Use specially formatted URLs to link to content within your app.(使用特殊格式的URL链接到应用程序中的内容)

前言

之前在实践Deep Link的时候,对URL Scheme进行了梳理。

概览

URL schemes提供了一种引用应用内资源的方法。 用户点击电子邮件中的自定义URL,例如,在指定的上下文中启动您的应用程序。 其他应用程序也可以触发您的应用程序使用特定的上下文数据启动; 例如,照片库应用可能显示指定的图像。

Apple支持与系统应用程序关联的常见方案,例如mailto,tel,sms和facetime。 您可以定义自己的自定义方案并注册您的应用程序以支持它。

简而言之:URL schemes的应用场景就是唤起App。

使用

// OR:  myphotoapp://xxx 这种形式也可以
let url = URL(string: "myphotoapp:Vacation?index=1")

UIApplication.shared.open(url!) { (result) in
    if result {
       // The URL was delivered successfully!
    }
}
// 根据业务需求做参数处理 
func application(_ application: UIApplication,
                 open url: URL,
                 options: [UIApplicationOpenURLOptionsKey : Any] = [:] ) -> Bool {
    
    // Determine who sent the URL.
    let sendingAppID = options[.sourceApplication]
    print("source application = \(sendingAppID ?? "Unknown")")
    
    // Process the URL.
    guard let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
        let albumPath = components.path,
        let params = components.queryItems else {
            print("Invalid URL or album path missing")
            return false
    }
    
    if let photoIndex = params.first(where: { $0.name == "index" })?.value {
        print("albumPath = \(albumPath)")
        print("photoIndex = \(photoIndex)")
        return true
    } else {
        print("Photo index missing")
        return false
    }
}

以上URL Scheme的使用内容主要来源于Apple的Developer Documentation。

缺点

URL Scheme可能会被劫持带来安全隐患。

URL Schemes为您的应用程序提供了潜在的攻击载体,因此请确保验证所有URL参数并丢弃任何格式错误的URL。 另外,将可用操作限制为不冒用户数据风险的操作。 例如,不允许其他应用直接删除内容或访问有关用户的敏感信息。 在测试URL处理代码时,请确保您的测试用例包含格式错误的URL。 —— Apple Warning(翻译)

场景

URL Schemes的使用场景有上面提到:

显然在Deep Link上的应用不是最好的,尤其是在信息流方面的App。Deep Link的需求是1、如果安装了App,那么直接打开App 2、如果没有安装App,那么引导到下载页。很显然URL Schemes的方式无法满足第二个需求。

While custom URL schemes are an acceptable form of deep linking, universal links are strongly recommended as a best practice. —— Apple Important

其他相关

let result = UIApplication.shared.canOpenURL(URL(string: "alipay://")!)

Deep Link

上面提到的Deep Link最佳实践其实是Universal links,可以学习下这篇deeplink唤醒app

上一篇 下一篇

猜你喜欢

热点阅读