Skip to content

Instantly share code, notes, and snippets.

@markvanwijnen
Last active March 21, 2021 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markvanwijnen/7f395b8392127a71f23f013ff9b2c233 to your computer and use it in GitHub Desktop.
Save markvanwijnen/7f395b8392127a71f23f013ff9b2c233 to your computer and use it in GitHub Desktop.
private var subscriptions: [String: AnyCancellable] = [:] // 1
func authorize() {
// 2
guard !self.authorizationSheetIsPresented else { return }
self.authorizationSheetIsPresented = true
// 3
self.subscriptions["oAuthRequestTokenSubscriber"] =
self.oAuthRequestTokenPublisher()
.receive(on: DispatchQueue.main) // 4
.sink(receiveCompletion: { completion in // 5
switch completion {
case .finished: ()
case .failure(_):
// Handle Errors
self.authorizationSheetIsPresented = false
}
self.subscriptions.removeValue(forKey: "oAuthRequestTokenSubscriber") // 6
}, receiveValue: { [weak self] temporaryCredentials in // 7
guard let self = self else { return }
// 8
guard let authorizationURL = URL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(temporaryCredentials.requestToken)")
else { return }
self.authorizationURL = authorizationURL // 9
self.subscriptions["onOAuthRedirect"] =
self.onOAuthRedirect // 10
.sink(receiveValue: { [weak self] url in
guard let self = self else { return }
self.subscriptions.removeValue(forKey: "onOAuthRedirect") // 11
self.authorizationSheetIsPresented = false // 12
self.authorizationURL = nil // 13
if let parameters = url.query?.urlQueryItems {
// 14
guard let oAuthToken = parameters["oauth_token"],
let oAuthVerifier = parameters["oauth_verifier"]
else {
// Handle error for unexpected response
return
}
if oAuthToken != temporaryCredentials.requestToken {
// Handle error for tokens do not match
return
}
print(oAuthToken)
print(oAuthVerifier)
// Continue with obtaining the access tokens
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment