Skip to content

Instantly share code, notes, and snippets.

@cozzin
Created September 24, 2020 02:22
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 cozzin/799bd3fe6305c1ac4c4f793d74398ecb to your computer and use it in GitHub Desktop.
Save cozzin/799bd3fe6305c1ac4c4f793d74398ecb to your computer and use it in GitHub Desktop.
Using WKWebview to get userAgent synchronously
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