Skip to content

Instantly share code, notes, and snippets.

@wotjd
Created October 4, 2022 17:38
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 wotjd/74c76540026557f8b356bde51cea36d4 to your computer and use it in GitHub Desktop.
Save wotjd/74c76540026557f8b356bde51cea36d4 to your computer and use it in GitHub Desktop.
Sign in with Apple + Combine (CombineCocoa)
import AuthenticationServices
import Combine
import CombineCocoa
extension ASAuthorizationController {
private var delegateProxy: AuthorizationControllerDelegateProxy {
.createDelegateProxy(for: self)
}
var didCompleteWithAuthroizationPublisher: AnyPublisher<ASAuthorization, Never> {
let selector = #selector(ASAuthorizationControllerDelegate.authorizationController(controller:didCompleteWithAuthorization:))
return self.delegateProxy.interceptSelectorPublisher(selector)
.compactMap { $0[1] as? ASAuthorization }
.eraseToAnyPublisher()
}
var didCompleteWithErrorPublisher: AnyPublisher<Error, Never> {
let selector = #selector(ASAuthorizationControllerDelegate.authorizationController(controller:didCompleteWithError:))
return self.delegateProxy.interceptSelectorPublisher(selector)
.compactMap { $0[1] as? Error }
.eraseToAnyPublisher()
}
func performRequestsPublisher(options: RequestOptions = []) -> AnyPublisher<ASAuthorization, Error> {
Deferred {
defer { self.performRequests(options: options) }
return Publishers
.Merge(
self.didCompleteWithAuthroizationPublisher
.setFailureType(to: ASAuthorizationError.self)
.mapError { $0 as Error },
self.didCompleteWithErrorPublisher
.flatMap { Fail(error: $0) }
)
}
.eraseToAnyPublisher()
}
}
private class AuthorizationControllerDelegateProxy: DelegateProxy, ASAuthorizationControllerDelegate, DelegateProxyType {
func setDelegate(to object: ASAuthorizationController) {
object.delegate = self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment