I tried to authenticate my app with spotifys api in order to get the users favorite songs but couldn’t get through the OAuth2 protocol.
I’ve tried the rever tutorial but It didn’t cache the tokens nor did it work properly.
I’ve looked at the AppAuth IOS Github repo and managed to include it but failed with SwiftUI.
My question is now regarding Appauth or any other oauth2 libraries: do I have to manually wrap all uidelegate an protocol classes in order to use it with swift ui?
I managed to reference The appdelegate in the main entry of my swiftui app but when it comes to this:
appDelegate.currentAuthorizationFlow =
OIDAuthState.authState(byPresenting: request, presenting: self)
It fails when passing my view controller as presenting self since it is not inherited by an ’’’extension AppAuthExampleViewController: OIDAuthStateChangeDelegate, OIDAuthStateErrorDelegate’’’ which however is not allowed by the view to inherit. This is where I am stuck.
Is there a trick or another solution for swiftui with oauth2 and not wrapping swift/storyboard based authentication projects and still managing user tokens/log in credentials? Currently, I’m slightly brain afk.
2
Answers
The only thing the AppAuth libraries should require is a view controller, which I’ve tended to provide like this in SwiftUI apps:
I adapt the OAuth libraries I use into an interface that is useful to the rest of the app. My personal preference with AppAuth has been to avoid the AuthState and design my own token storage, though you may have different preferences.
Here is some working code for a SwiftUI app, as something to compare against. It shows that use of AppAuth can be done without much impact on the app’s main code.
AppAuth library needs to have a UIViewController as a presenter.
So in your AuthManager class, you can use this code.
It’s better to use UIWindowScene, which Apple suggests in case of supporting multiple scenes: