我正在製作一個應用程序,通過使用if語句檢測是否存在與互聯網的連接,當有互聯網時,除了沒有互聯網連接,什麼也不做,然後警告視圖說應用程序需要互聯網我管理髮現可達性,但實施我的viewDidLoad()uialertview似乎不工作。 我使用這個:檢測互聯網連接並顯示UIAlertview Swift 3
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
}
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection
}
}
然後在我的視圖控制器類:
override func viewDidLoad() {
if Reachability.isConnectedToNetwork() == true
{
print("Connected")
}
else
{
let controller = UIAlertController(title: "No Internet Detected", message: "This app requires an Internet connection", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
controller.addAction(ok)
controller.addAction(cancel)
present(controller, animated: true, completion: nil)
}
super.viewDidLoad()
//...
}
,看起來像alertview不彈出 什麼建議嗎?或幫助? 謝謝
嘗試。 – rmaddy
@rmaddy你能詳細解釋一下嗎?即時通訊新的迅速或ios和IAM加載我所有的代碼到viewdidload()atm – killburn
沒有什麼可說的。只需從'viewDidLoad'方法中移動可達性相關的代碼,並將其放入'viewDidAppear'方法中。 – rmaddy