我想做代码,无论我的iPhone是否与互联网连接,无论是wifi还是蜂窝网络。
现在我的问题是当我通过蜂窝连接执行我的应用程序时,我没有收到任何错误和应用程序运行和Web服务调用正常工作但是当我将互联网连接从蜂窝网络切换到wifi网络时,我得到警告&#34 ;没有互联网连接"即使intetnet在wifi上正常工作。
你能帮助我找到这个问题吗?
代码:
在viewDidLoad()中,我正在调用此函数:
callWSForGetProjectLeadersList()
在以下功能中,我正在检查互联网连接是否可用:isConnectedToNetwork()
func callWSForGetProjectLeadersList()
{
if Reachability.isConnectedToNetwork()
{
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
do
{
try WebServiceCall.webServiceCall("getUsers", parameters: nil, tag: "getUsers", reference: self, type: "POST")
}
catch
{
CommonFunctions.exceptionAlert()
return
}
}
}
else
{
// TODO : This is part should not run while Internet connection is avail.
DispatchQueue.main.async(execute: {
ActivityIndicator.stopAnimating()
Toast.showMessage(self.view, msg: "Please check your internet connection and try after sometime", time: 2.0)
})
}
}
现在在具有ToCheck Internet连接的以下类代码中:
public class Reachability {
class 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
}
当我在wifi上运行时,它会调用以下函数:
class func networkAlert()
{
DispatchQueue.main.async(execute: {
let alert = UIAlertView(title: "No Internet!", message: "No working Internet connection is Found.", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
})
}