IOS WebView實現

ViewController.swift



import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
    
    var webView: WKWebView!
    var reachability: Reachability?
    let hostNames = ["baidu.com", "qq.com", "apple.com"]
    var hostIndex = 0
    var gameurl = "http://www.37wan.com/"
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
        
        UIApplication.shared.isIdleTimerDisabled = true
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let myURL = URL(string:gameurl)
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
        // Do any additional setup after loading the view, typically from a nib.
        //創建一個字符串常量,作爲是否啓動過的標示名稱
        let EVERLAUNCHED = "everlaunched"
        //再創建一個字符串常量,作爲首次啓動的標識符名稱
        let FIRSTLAUNCH = "firstlaunch"
        //獲得變量的布爾值,當程序首次啓動時由於沒有設置過變量,所以默認值爲否
        if(!UserDefaults.standard.bool(forKey: EVERLAUNCHED))
        {
            //將標識是否啓動過的變量更該爲真,標示程序至少被啓動過一次
            UserDefaults.standard.set(true, forKey: EVERLAUNCHED)
            //將標示是否首次啓動的變量設爲真,標示程序是首次啓動
            UserDefaults.standard.set(true, forKey: FIRSTLAUNCH)
            //調用同步方法,立即保存修改
            UserDefaults.standard.synchronize()
        }
        else{
            //如果曾經啓動過程序,則變量的布爾值爲否
            UserDefaults.standard.set(false, forKey: FIRSTLAUNCH)
            //調用同步方法,立即保存修改
            UserDefaults.standard.synchronize()
        }
        //初始化一個字符串,作爲提示窗口的內容
        var message = "It's the first show"
        if(!UserDefaults.standard.bool(forKey: FIRSTLAUNCH))
        {
            message = "it's not first show"
            print(message)
            //let myURL = URL(string:gameurl)
            //let myRequest = URLRequest(url: myURL!)
            //webView.load(myRequest)
        }else{
            print(message)
        }
         //網絡檢測
        startHost(at: 0)
    }
    func startHost(at index: Int) {
        stopNotifier()
        setupReachability(hostNames[index], useClosures: true)
        startNotifier()
        //DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
        //    self.startHost(at: (index + 1) % 3)
        //}
    }
    
    func setupReachability(_ hostName: String?, useClosures: Bool) {
        let reachability: Reachability?
        if let hostName = hostName {
            reachability = try? Reachability(hostname: hostName)
        } else {
            reachability = try? Reachability()
        }
        self.reachability = reachability
        print("--- set up with host name: \(String(describing: hostName))")

        if useClosures {
            reachability?.whenReachable = { reachability in
                self.updateWhenReachable(reachability)
            }
            reachability?.whenUnreachable = { reachability in
                self.updateWhenNotReachable(reachability)
            }
        } else {
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(reachabilityChanged(_:)),
                name: .reachabilityChanged,
                object: reachability
            )
        }
    }
    
    func startNotifier() {
        print("--- start notifier")
        do {
            try reachability?.startNotifier()
        } catch {
            print("Unable to start\nnotifier")
            return
        }
    }
    
    func stopNotifier() {
        print("--- stop notifier")
        reachability?.stopNotifier()
        NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: nil)
        reachability = nil
    }
    
    func updateWhenReachable(_ reachability: Reachability) {
        //print("\(reachability.description) - \(reachability.connection)")
        if reachability.connection == .wifi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
        let myURL = URL(string:gameurl)
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
        stopNotifier()
    }
    
    func updateWhenNotReachable(_ reachability: Reachability) {
        print("\(reachability.description) - \(reachability.connection)")
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.startHost(at: 0)
        }
    }

    @objc func reachabilityChanged(_ note: Notification) {
        let reachability = note.object as! Reachability
        print("reachabilityChanged")
        if reachability.connection != .unavailable {
            //updateWhenReachable(reachability)
        } else {
            //updateWhenNotReachable(reachability)
        }
    }
    
    deinit {
        stopNotifier()
        print("deinit...")
    }
}

有些手機首次打開app白屏,主要是因爲首次打開app需要授權網絡訪問權限,因此加上檢測網絡狀態來解決這個問題。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章