首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以使用来自ASWebAuthenticationSession的SwiftUI?

是否可以使用来自ASWebAuthenticationSession的SwiftUI?
EN

Stack Overflow用户
提问于 2019-10-26 19:44:26
回答 1查看 3.4K关注 0票数 4

我想使用OAuth API对ASWebAuthenticationSession进行身份验证,但是从SwiftUI上看,它似乎是不可用的。这就是我想要的:

代码语言:javascript
复制
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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-30 03:07:48

我分三部分解决了这个问题:

首先,在SceneDelegate.swift设置期间捕获全局对象中的窗口。

代码语言:javascript
复制
var globalPresentationAnchor: ASPresentationAnchor? = nil
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // ...            
        globalPresentationAnchor = window
    }
}

然后,创建一个小的ViewController,将窗口对象提供给正在使用的ASWebAuthenticationSession

代码语言:javascript
复制
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作为演示者。

代码语言:javascript
复制
    let session = ASWebAuthenticationSession(/**/)
    session.presentationContextProvider = ShimViewController()
    session.start()
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58574143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档