ios 如何使用Swift获取用户代理,而不使用过时的WebView

tzcvj98z  于 2023-10-21  发布在  iOS
关注(0)|答案(4)|浏览(174)

我需要用户代理。我曾经使用UIWebView获得它,但现在已弃用。

let userAgent = UIWebView().stringByEvaluatingJavaScript(from: "navigator.userAgent")!
mwg9r5ms

mwg9r5ms1#

我们可以使用下面的代码片段获得userAgent

import UIKit
import WebKit

class ViewController: UIViewController{
 
    var WKwebView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getUserAgent()
    }
    
    func getUserAgent() {
        let webConfiguration = WKWebViewConfiguration()
        WKwebView = WKWebView(frame: .zero, configuration: webConfiguration)
        WKwebView.evaluateJavaScript(
            "navigator.userAgent", 
            completionHandler: { (result, error) in
                debugPrint(result as Any)
                debugPrint(error as Any)

                if let unwrappedUserAgent = result as? String {
                    print("userAgent: \(unwrappedUserAgent)")
                } else {
                    print("failed to get the user agent")
                }
            }
        )
    }    
}

输出:userAgent:Mozilla/5.0(iPhone; CPU iPhone OS 13_3 like Mac OS X)AppleWebKit/605.1.15(KHTML,like Gecko)移动的/15 E148

epggiuax

epggiuax2#

使用WebKit代替。

import WebKit

let webView = WKWebView()
webView.evaluateJavaScript("navigator.userAgent") { (result, error) in
    print(result as! String)
}

// Output 
Mozilla/5.0 (iPad; CPU OS 13_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
sqyvllje

sqyvllje3#

最好使用这段代码。

let userAgent = WKWebView().value(forKey: "userAgent")
fdx2calv

fdx2calv4#

Haiiro提供的同步功能更实用,这里是objective-c版本。

NSString *userAgent = [[[WKWebView alloc] init] valueForKey:@"userAgent"];

相关问题