我想使用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()
}
}}
它需要采用与SwiftUI视图不兼容的协议ASWebAuthenticationPresentationContextProviding。
我可以通过重定向到一个ViewController来克服这个问题,后者可以提供ASWebAuthenticationPresentationContextProviding,但这增加了一个额外的视图/导航步骤。
是否有任何方法可以使用ASWebAuthenticationSession从SwiftUI而不进入ViewController?
发布于 2019-10-30 03:07:48
我分三部分解决了这个问题:
首先,在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()https://stackoverflow.com/questions/58574143
复制相似问题