Created
September 24, 2020 02:22
-
-
Save cozzin/799bd3fe6305c1ac4c4f793d74398ecb to your computer and use it in GitHub Desktop.
Using WKWebview to get userAgent synchronously
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class UserAgentFetcher: NSObject { | |
private let webView: WKWebView = WKWebView(frame: .zero) | |
@objc | |
public func fetch() -> String { | |
dispatchPrecondition(condition: .onQueue(.main)) | |
var result: String? | |
webView.evaluateJavaScript("navigator.userAgent") { response, error in | |
if let error = error { | |
result = "" | |
return | |
} | |
result = response as? String ?? "" | |
} | |
while (result == nil) { | |
RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) | |
} | |
return result ?? "" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment