-
Notifications
You must be signed in to change notification settings - Fork 4
/
ASWebAuthenticationSession.swift
88 lines (75 loc) · 2.42 KB
/
ASWebAuthenticationSession.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
// ASWebAuthenticationSession.swift
// RxModal
//
// Created by Jérôme Alves on 10/02/2021.
//
import UIKit
import AuthenticationServices
import RxSwift
extension RxModal {
@available(iOS 12.0, *)
public static func webAuthenticationSession(
presenter: Presenter = .keyWindow,
url: URL,
callbackURLScheme: String,
configuration: @escaping (ASWebAuthenticationSession) -> Void = { _ in }
) -> Single<URL> {
.using {
try RxWebAuthenticationSessionCoordinator(
presenter: presenter,
url: url,
callbackURLScheme: callbackURLScheme,
configuration: configuration
)
} primitiveSequenceFactory: { coordinator in
coordinator.result.asSingle()
}
}
}
@available(iOS 12.0, *)
private class RxWebAuthenticationSessionCoordinator: NSObject, ASWebAuthenticationPresentationContextProviding, Disposable {
var window: UIWindow!
let session: ASWebAuthenticationSession
let result: PublishSubject<URL>
init(
presenter: Presenter,
url: URL,
callbackURLScheme: String,
configuration: @escaping (ASWebAuthenticationSession) -> Void
) throws {
let result = PublishSubject<URL>()
let session = ASWebAuthenticationSession(
url: url,
callbackURLScheme: callbackURLScheme,
completionHandler: { url, error in
if let error = error {
return result.onError(error)
}
guard let url = url else {
return result.onError(RxModalError.unsupported)
}
result.onNext(url)
result.onCompleted()
}
)
configuration(session)
self.result = result
self.session = session
super.init()
if #available(iOS 13.0, *) {
guard let window = presenter()?.viewIfLoaded?.window else {
throw RxModalError.missingPresenter
}
self.window = window
self.session.presentationContextProvider = self
}
self.session.start()
}
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return window
}
public func dispose() {
session.cancel()
}
}