iOS 进程间的通信方式—Custom URL Scheme

693 阅读1分钟

关键词:进程通信,URL Scheme

communication.webp

Custom URL Scheme

自定义 URL scheme 提供了一种访问应用内资源的方法。 例如,用户在电子邮件中点击自定义 URL,会在指定的上下文中启动您的应用程序。其他应用程序也可以使用特定的上下文数据启动您的应用程序。常见使用场景:分享,登录等。

首先看效果

share.gif

如何设置 URL Scheme?

1、SourceApp
let url = URL(string: "ehr://employDetail?id=999")
UIApplication.shared.open(url!) { success in

}   
2、DestinationApp
  • 增加 URL Types image.png

  • 若 App 只包含 AppDelegate 文件(老项目),则需要在 func application(_:, open url:, options:) 中拦截 URL

// AppDelegate.swift
extension AppDelegate {  
    func application(_ appUIApplicationopen urlURLoptions: [UIApplication.OpenURLOptionsKeyAny]) -> Bool {  
        print(url.absolueString)  
        return true  
    }  
}
  • 若 App 包含 SceneDelegate 文件(新项目),同时 App 未启动, 则需要在 func scene(_:willConnectTo:options:) 中拦截 URL
//  SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let _ = (scene as? UIWindowScene) else { return }
    guard let url = connectionOptions.urlContexts.first?.url else {
        return
    }
    print(url.absoluteString)
}
  • 若 App 包含 SceneDelegate 文件(新项目),同时 App 已经启动, 则需要在 func scene(_:​open​URLContexts:) 中拦截 URL
//  SceneDelegate.swift
let shareDataWithinAppsNotification = Notification.Name("shareDataWithinApps")
extension SceneDelegate {  
    func scene(_ sceneUISceneopenURLContexts URLContextsSet<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else {  
            return  
        }  
        print(url.absoluteString)
    }  
}

注意事项

  • 该方案需严格验证 URL 参数,限制操作权限,防止被恶意攻击。
  • 若多个 App 使用同一个 scheme,则跳转方案会出现各种奇怪问题,所以要保证 scheme 的唯一性。
  • 为了保证参数正确解析,请使用 NSURLComponents APIs 解析参数。

referance

demo