我一直在尝试弄清楚如何将 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/