0

我正在使用可访问性 swift 来处理 swift 4 中的互联网状况。我可以成功检测互联网是否正常工作,如果互联网可用,我的代码会成功导航到所需的页面,但如果互联网不可用,它会显示警报消息,没有互联网连接可用。

override func viewDidLoad() {
        super.viewDidLoad()
        do{
            reachability = try Reachability()

            try reachability?.startNotifier()
        }catch{
            print("could not start reachability notifier")
        }
    }


 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.checkNetworkStatus()

    }


func checkNetworkStatus() {
        let alert = UIAlertController(title: "", message: "无网络连接", preferredStyle: .alert)
        if reachability?.isReachable == true {
            alert.dismiss(animated: true, completion:nil)
            queryObj()
        } else {

            alert.addAction(UIAlertAction(title: "好", style: .default, handler: { action in
                switch action.style{
                case .default:
                    print("default")
                case .cancel:
                    print("cancel")
                case .destructive:
                    print("destructive")
                default :
                    print("default")
                }}))
            self.present(alert, animated: true, completion: nil)
            let when = DispatchTime.now() + 1
            DispatchQueue.main.asyncAfter(deadline: when){
                self.checkNetworkStatus()
            }
        }
    }

func queryObj(){

            Alamofire.request(self.base_url ).responseJSON { response in
                if
                    let result = response.result.value
                {
                    let JSON = result as! NSDictionary
                    let server_status = JSON.object(forKey: "code") as? String
                    if server_status == "200"{
                        let preResult = JSON.object(forKey: "result") as! NSDictionary
                        let result1 = preResult.object(forKey: "iconimage") as! String
                        let supportViewController = self.storyboard!.instantiateViewController(withIdentifier: "support") as! SupportViewController
                        supportViewController.supportURL = result1
                        self.present(supportViewController, animated: false, completion: nil)

                        return
                    }else{
                        let mainViewController = self.storyboard!.instantiateViewController(withIdentifier: "nav")
                        self.present(mainViewController, animated: false, completion: nil)
                    }
                }else{
                    self.queryObj()
                }

            }
       }
  • 怀疑

假设如果最初,用户已关闭移动数据...此代码将显示“没有互联网连接”,但即使用户接入互联网,它也不会推送到其他页面并点击我的 url,这应该是它应该做。

我该如何处理这种情况?

我希望代码在用户打开移动数据时立即工作。请帮我解决这个小问题。任何帮助或指导将不胜感激。在此先感谢!

4

2 回答 2

2

只需快速浏览一下文档:https ://github.com/ashleymills/Reachability.swift

override func viewDidLoad() {
    super.viewDidLoad()
    let reachability = try! Reachability()
    NotificationCenter.default.addObserver(self, selector: #selector(checkNetworkStatus(note:)), name: .reachabilityChanged, object: reachability)
    do{
        try reachability.startNotifier()
    }catch{
        print("could not start reachability notifier")
    }
}

@objc func checkNetworkStatus(note: Notification) {
    let reachability = note.object as! Reachability
    let alert = UIAlertController(title: "", message: "无网络连接", preferredStyle: .alert)
    if reachability?.isReachable == true {
        alert.dismiss(animated: true, completion:nil)
        queryObj()
    } else {

        alert.addAction(UIAlertAction(title: "好", style: .default, handler: { action in
            switch action.style{
            case .default:
                print("default")
            case .cancel:
                print("cancel")
            case .destructive:
                print("destructive")
            default :
                print("default")
            }}))
        self.present(alert, animated: true, completion: nil)
        let when = DispatchTime.now() + 1
        DispatchQueue.main.asyncAfter(deadline: when){
            self.checkNetworkStatus()
        }
    }
}
于 2019-12-12T09:32:13.823 回答
-1

试试这个代码: -

import SystemConfiguration

和你班上的这个功能

func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    /* Only Working for WIFI
     let isReachable = flags == .reachable
     let needsConnection = flags == .connectionRequired

     return isReachable && !needsConnection
     */

    // Working for Cellular and WIFI
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    let ret = (isReachable && !needsConnection)

    return ret

}

用途:-

if isConnectedToNetwork(){

        print("Internet Connection Available!")
}
else
{
        print("Internet Connection not Available!")
}
于 2019-12-12T09:58:10.907 回答