我想使用 OAuth API 进行身份验证ASWebAuthenticationSession
但它似乎无法从 SwiftUI 中使用。
这就是我想要的:
struct ContentView: View: ASWebAuthenticationPresentationContextProviding {
var body: some View {
NavigationView {
VStack {
Button("Hello World", {
// Run oauth flow
}
}
}
.navigationBarTitle(Text("Greed of Savin"))
.navigationViewStyle(StackNavigationViewStyle())
}
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return BungieApi.sharedInstance.presentationAnchor ?? ASPresentationAnchor()
}
}
}
它需要采用协议ASWebAuthenticationPresentationContextProviding
它与 SwiftUI 的视图不兼容。
我可以通过重定向到 ViewController 来解决这个问题,然后该 ViewController 可以提供ASWebAuthenticationPresentationContextProviding
,但这会增加一个额外的视图/导航步骤。
有什么办法可以使用吗ASWebAuthenticationSession
从 SwiftUI 而不进入 ViewController?
我分三个部分解决了这个问题:
首先,在设置期间捕获全局对象中的窗口SceneDelegate.swift
:
var globalPresentationAnchor: ASPresentationAnchor? = nil
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// ...
globalPresentationAnchor = window
}
}
然后,创建一个小的 ViewController 来将该窗口对象提供给使用ASWebAuthenticationSession
:
class ShimViewController: UIViewController, ASWebAuthenticationPresentationContextProviding
{
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
// Perhaps I don't need the window object at all, and can just use:
// return ASPresentationAnchor()
return globalPresentationAnchor ?? ASPresentationAnchor()
}
}
最后,调用身份验证 API,提供 ShimViewController 作为演示者。
let session = ASWebAuthenticationSession(/**/)
session.presentationContextProvider = ShimViewController()
session.start()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)