当前位置:网站首页>Swift extension networkutil (network monitoring) (source code)

Swift extension networkutil (network monitoring) (source code)

2022-06-24 08:05:00 Fenghanxu

I always feel that what I write is not technology , But feelings , One tutorial after another is the trace of one's own journey . Success with expertise is the most replicable , I hope my path will make you less detours , I hope I can help you erase the dust of knowledge , I hope I can help you clarify the context of knowledge , I hope there will be you and me on the top of technology in the future .

(Swift)NetworkUtil Monitor the network

Preface

2022.06.23 Today I wrote a ios13 And above monitor network encapsulation . You can get the current network status , When the network changes, you will be notified

On the subject

It is very convenient to use

1. Enable network monitoring when starting
 Insert picture description here

2. Then you can use it wherever you want
 Insert picture description here

import UIKit
import SnapKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Get the enumeration of network status 
        print("connectType: \(NetworkUtil.shared.connectType.rawValue)")
        // Get the text value of the network status 
        print("readableConnectType: \(NetworkUtil.shared.readableConnectType)")
        // Register for network monitoring 
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(onNetworkChange),
            name: Notification.Name("onNetworkChange"),
            object: nil
        )
    }
  
    // Once the network changes, it will be notified 
    @objc func onNetworkChange(notification : Notification){
        DispatchQueue.main.async {
            guard
                let dictionary = notification.userInfo,
                let type = dictionary["type"] as? Int
            else {
                return
            }

            let connectType = NetworkUtil.ConnectType(rawValue: type)!

            switch (connectType) {
            case .unknown:
                print(" No network available at present ")
            default:
                break
            }
        }
    }
}
原网站

版权声明
本文为[Fenghanxu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240434142005.html