How to get the user agent on iOS?

后端 未结 6 2016
天涯浪人
天涯浪人 2020-12-14 19:59

Is there a way on iOS to get the user agent of the device? I don\'t want to hard code it since I need the user agent for all devices and I need to append the user agent to a

6条回答
  •  旧巷少年郎
    2020-12-14 20:50

    (iOS 8.0, *)

    Since UIWebView is deprecated in iOS 12, you should use WKWebView instead.

    Since WKWebView.evaluateJavaScript(_:) result is now async, this implementation solve a common requirement to have userAgent available in your own REST api call.

    import WebKit
    
    class UAString {
    
        static var userAgent : String = ""
    
        @discardableResult init(view parent: UIView) {
    
            if UAString.userAgent.isEmpty {
    
                let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
    
                webView.translatesAutoresizingMaskIntoConstraints = false
                parent.addSubview(webView)
    
                webView.evaluateJavaScript("navigator.userAgent") { result, _ in
                    UAString.userAgent = result as? String ?? ""
                }
            }
        }
    
    }
    

    Now last part you can implement this class in your initial view controller as follow:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        UAString(view: self.view)
    }
    

    then you can access the attribute as UAString.userAgent

提交回复
热议问题