在开发 iOS 和 macOS 应用时候,经常需要处理通过外部 Scheme 来跳转 App,并执行相关动作的场景,例如处理网站或 SDK 的 Oauth 登录。在常规的 AppKit 框架下已经有非常成熟的最佳实践可供参考,但当我们来到 SwiftUI 2.0 的世界中,当 AppDelegate 不复存在的时候,应该如何处理 Scheme 的跳转,以下是一点微小的实践和探索。

OpenUrl

SwiftUI 官方提供了一个类似 UIApplication 中 open(_:options:completionHandler:) 的 Modifier:onOpenURL

Registers a handler to invoke when the view receives a url for the scene or window the view is in.

func onOpenURL(perform action: @escaping (URL) -> ()) -> some View

以 OauthSwift 为例,将 handleURL 相关的方法和代理放入 onOpenURL 中就可以了

.onOpenURL { (url) in
    /// 处理 Oauth
    OAuthSwift.handle(url: url)
}