import RxSwift
import RxCocoa
import Network
class NetworkAuthorizationManager {
let isAuthorized = BehaviorRelay<Bool>(value: false)
init() {
checkNetworkAuthorization()
}
private func checkNetworkAuthorization() {
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
self.isAuthorized.accept(path.status ==.satisfied)
}
let queue = DispatchQueue(label: "NetworkMonitor")
monitor.start(queue: queue)
}
}
class YourViewController: UIViewController {
let disposeBag = DisposeBag()
let networkAuthorizationManager = NetworkAuthorizationManager()
override func viewDidLoad() {
super.viewDidLoad()
networkAuthorizationManager.isAuthorized
.subscribe(onNext: { authorized in
if authorized {
// 加载页面数据
} else {
// 显示系统弹出层请求网络授权
let alertController = UIAlertController(title: "网络授权", message: "应用需要网络权限以正常工作,请前往设置授予权限", preferredStyle:.alert)
alertController.addAction(UIAlertAction(title: "确定", style:.default, handler: { _ in
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!)
}
}))
self.present(alertController, animated: true, completion: nil)
}
})
.disposed(by: disposeBag)
}
}