gpt4 book ai didi

ios - 检查互联网连接时,隐藏的 UIVIEW 无法快速工作

转载 作者:行者123 更新时间:2023-11-30 11:18:33 25 4
gpt4 key购买 nike

当我试图查明互联网是否活跃时。在检查互联网之前,我尝试显示加载屏幕。但需要上网查询功能结果后才能生效。

我的互联网检查代码是

class Activeinternet: UIViewController {


class func isConnectedToNetwork() -> Bool {

var Status:Bool = false
let url = NSURL(string: "https://google.com/")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "HEAD"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 4.0
var response: URLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest as URLRequest, returning:&response) as NSData
} catch let error as NSError {
// reponseError = error
urlData = nil
}



if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
Status = true
}
}

return Status

}


}

调用互联网检查

self.internetloadsview.isHidden = false
self.internetloadsindicator.startAnimating()
if Activeinternet.isConnectedToNetwork() == true {
self.internetloadsview.isHidden = true
self.internetdwnmsg.isHidden = true
}
else{
self.internetdwnmsg.isHidden = false
}

一切正常。但是

self.internetloadsview.isHidden = false
self.internetloadsindicator.startAnimating()

此代码在主动互联网检查结果后工作

我想在互联网事件 isConnectedToNetwork 调用之前显示 uiview

提前致谢

最佳答案

您正在以阻塞主线程的同步方式调用它。您必须在async中调用它并在完成处理程序中处理调用。

func isConnectedToNetwork( completionHandler completion: @escaping (Bool)-> Void) {

if let url = URL(string: "https://google.com/") {
var request = URLRequest(url: url)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) {
data, response, error in

if error == nil {
completion(true)
} else {
completion(false)
}
}
task.resume()
}
}

并使用这样的完成 block 调用此函数

 isConnectedToNetwork { (isSuccess) in
if isSuccess {
DispatchQueue.main.async {
self.label1.text = "Internet is Connected"
}
}
else{
DispatchQueue.main.async {
self.label1.text = "Internet is not connected"

}
}

}

关于ios - 检查互联网连接时,隐藏的 UIVIEW 无法快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51542671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com