Skip to content

Commit e34b785

Browse files
committed
Consider App Extension environment
1 parent f3be0d1 commit e34b785

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

Sources/RxKeyboard.swift

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ public class RxKeyboard: NSObject {
3333

3434
// MARK: Private
3535

36+
fileprivate let window = RxKeyboard.applicationWindow()
3637
fileprivate let disposeBag = DisposeBag()
3738
fileprivate let panRecognizer = UIPanGestureRecognizer()
3839

@@ -91,9 +92,9 @@ public class RxKeyboard: NSObject {
9192
// pan gesture
9293
let didPan = self.panRecognizer.rx.event
9394
.withLatestFrom(frameVariable.asObservable()) { ($0, $1) }
94-
.flatMap { (gestureRecognizer, frame) -> Observable<CGRect> in
95+
.flatMap { [weak self] (gestureRecognizer, frame) -> Observable<CGRect> in
9596
guard case .changed = gestureRecognizer.state,
96-
let window = UIApplication.shared.windows.first,
97+
let window = self?.window,
9798
frame.origin.y < UIScreen.main.bounds.height
9899
else { return .empty() }
99100
let origin = gestureRecognizer.location(in: window)
@@ -112,12 +113,23 @@ public class RxKeyboard: NSObject {
112113
NotificationCenter.default.rx.notification(.UIApplicationDidFinishLaunching)
113114
.map { _ in Void() }
114115
.startWith(Void()) // when RxKeyboard is initialized before UIApplication.window is created
115-
.subscribe(onNext: { _ in
116-
UIApplication.shared.windows.first?.addGestureRecognizer(self.panRecognizer)
116+
.subscribe(onNext: { [weak self] _ in
117+
guard let `self` = self else { return }
118+
self.window?.addGestureRecognizer(self.panRecognizer)
117119
})
118120
.addDisposableTo(self.disposeBag)
119121
}
120122

123+
/// Returns the first window of `UIApplication.shared`. Returns `nil` if the application has no
124+
/// window. (e.g. App Extension)
125+
private class func applicationWindow() -> UIWindow? {
126+
// use objc selector to get shared UIApplication instance from App Extension
127+
let selector = NSSelectorFromString("sharedApplication")
128+
guard UIApplication.responds(to: selector) else { return nil }
129+
let application = UIApplication.perform(selector).takeRetainedValue() as? UIApplication
130+
return application?.windows.first
131+
}
132+
121133
}
122134

123135

0 commit comments

Comments
 (0)