swift - SWIFTUI 中的 ASWebAuthenticationSession

标签 swift swiftui ios13 xcode11

我一直在尝试弄清楚如何将 ASWebAuthenticationSession(通过 Oauth 执行登录)与 SwiftUI 集成。我在任何地方都找不到相同的在线文档,并且想知道是否有更多 SwiftUI 和 iOS 开发经验的人可以告诉我如何实现一些目标。我目前需要一个系统,供用户单击“登录”按钮,然后打开一个 ASWebAuthSession 并允许用户登录,然后将他们重定向回我的应用程序并加载另一个 SwiftUI View 。

我的 ContentView 中有一个按钮调用此函数:

func getAuthTokenWithWebLogin() {

    let authURL = URL(string: "https://test-login.blabla.no/connect/authorize?scope=openid%20profile%20AppFramework%20offline_access&response_type=code&client_id=<blalblalba>&redirect_uri=https://integration-partner/post-login")
    let callbackUrlScheme = "no.blabla:/oauthdirect"

    webAuthSession = ASWebAuthenticationSession.init(url: authURL!, callbackURLScheme: callbackUrlScheme, completionHandler: { (callBack:URL?, error:Error?) in

        // handle auth response
        guard error == nil, let successURL = callBack else {
            return
        }

        let oauthToken = NSURLComponents(string: (successURL.absoluteString))?.queryItems?.filter({$0.name == "code"}).first

        // Do what you now that you've got the token, or use the callBack URL
        print(oauthToken ?? "No OAuth Token")
    })

    // Kick it off
    webAuthSession?.start()

}

但我收到此错误:

Cannot start ASWebAuthenticationSession without providing presentation context. Set presentationContextProvider before calling -start.

我应该如何在 SwiftUI 中执行此操作?任何例子都会很棒!

最佳答案

BetterSafariView 中使用 .webAuthenticationSession(isPresented:content) 修饰符,您可以在 SwiftUI 中轻松使用 ASWebAuthenticationSession。它处理与提供演示上下文相关的工作。

import SwiftUI
import BetterSafariView

struct ContentView: View {
    
    @State private var startingWebAuthenticationSession = false
    
    var body: some View {
        Button("Start WebAuthenticationSession") {
            self.startingWebAuthenticationSession = true
        }
        .webAuthenticationSession(isPresented: $startingWebAuthenticationSession) {
            WebAuthenticationSession(
                url: URL(string: "https://github.com/login/oauth/authorize?client_id=\(clientID)")!,
                callbackURLScheme: "myapp"
            ) { callbackURL, error in
                print(callbackURL, error)
            }
        }
    }
}

关于swift - SWIFTUI 中的 ASWebAuthenticationSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59814678/

相关文章:

ios - 使用带有 swift 的格式化文本字段创建具有安全文本输入的 PIN 码

swift - 无法在 ios13 swift 以上播放本地 mp3

swift - Swift 自定义字体剪裁的顶部

ios - 类型 'Model' 不符合协议(protocol) 'Decodable'/Encodable

ios - SwiftUI VStack 右对齐单个元素

ios - iOS 13 和 14 上的 NSKeyValuePopPendingNotificationLocal 崩溃

ios - pod WEPopover 弹出菜单未显示为 currentTopViewcontroller。相反,它会转到 currentTopviewController View 层次结构的后面

iOS Localizations changing, native region

ios - UITableViewCell 高度不正确,sizeToFit 尺寸不正确

swift - 在 Swift 中从 Radius 中的 GeoFire 检索 key