Skip to content

Commit 8e9a96d

Browse files
Merge pull request #194 from teads/webviewHelper-url-observer
migrate webview url observer to KVO NSKeyValueObservation API
2 parents 125ba42 + 2fea762 commit 8e9a96d

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

TeadsSampleApp/WebViewHelper/TeadsWebViewHelper.swift

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,6 @@ import WebKit
7676
private var slotOpener: (() -> Void)?
7777
private var slotOpportunity: ((WKWebView, SlotPosition) -> Void)?
7878

79-
private static let urlKeyPath = NSExpression(forKeyPath: \WKWebView.url).keyPath
80-
8179
/// Init the Teads webView helper
8280
///
8381
/// Handles slot position injection from TeadsSDK
@@ -95,8 +93,15 @@ import WebKit
9593
self.delegate = delegate
9694
super.init()
9795

98-
// URL Change observer
99-
webView.addObserver(self, forKeyPath: Self.urlKeyPath, options: .new, context: nil)
96+
/// Track url requests change in order to reset adView and position tracking
97+
/// When position is located a new time, alert through ``TeadsWebViewHelperDelegate/webViewHelperSlotFoundSuccessfully()``
98+
webViewObservation = webView.observe(\.url, options: [.old, .new]) { [weak self] _, changes in
99+
if changes.oldValue != changes.newValue {
100+
self?.adView?.removeFromSuperview()
101+
self?.containerView?.removeFromSuperview()
102+
self?.slotPosition = nil
103+
}
104+
}
100105

101106
// add message handler method name to communicate with the wkwebview
102107
JSBootstrapOutput.allCases.map(\.rawValue).forEach {
@@ -120,18 +125,6 @@ import WebKit
120125
}
121126
}
122127
webViewObservation = nil
123-
NotificationCenter.default.removeObserver(self)
124-
}
125-
126-
/// Track url requests change in order to reset adView and position tracking
127-
/// When position is located a new time, alert through ``TeadsWebViewHelperDelegate/webViewHelperSlotFoundSuccessfully()``
128-
override public func observeValue(forKeyPath keyPath: String?, of _: Any?, change: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) {
129-
if keyPath == Self.urlKeyPath,
130-
let _ = change?[NSKeyValueChangeKey.newKey] {
131-
adView?.removeFromSuperview()
132-
containerView?.removeFromSuperview()
133-
slotPosition = nil
134-
}
135128
}
136129

137130
/// Inject Teads' bootstrap in the webview
@@ -473,7 +466,7 @@ extension TeadsWebViewHelper {
473466
/// When registering WKWeakScriptHandler, WKWebView create a strong reference to handler
474467
/// This leads to retain cycle between webView <-> owner and webView <-> scriptHandler
475468
/// In order to avoid retain cycle
476-
class WKWeakScriptHandler: NSObject, WKScriptMessageHandler {
469+
final class WKWeakScriptHandler: NSObject, WKScriptMessageHandler {
477470
weak var delegate: WKScriptMessageHandler?
478471

479472
init(delegate: WKScriptMessageHandler) {

0 commit comments

Comments
 (0)