2017-06-29 32 views
-3

如何通知用户与swift没有网络连接3.我已经尝试了一堆解决方案,目前为止他们都没有工作。我不在寻找网络连接的速度如果没有网络连接,则显示警报

+0

的可能的复制[如何使用SWIFT检查网络速度(https://stackoverflow.com/questions/38635804/how-to-check- (网络速度使用迅速) – Rob

+0

在使用应用程序(IOS xcode swift)期间丢失可达性连接时弹出警报的可能重复](https://stackoverflow.com/questions/31400192/popup-alert-when -reachability-connection-is-lost-during-using-the-app-ios-xcode) – fpg1503

回答

1

有很多资源显示如何检查Internet连接。例如,从this

func isInternetAvailable() -> Bool 
    { 
     var zeroAddress = sockaddr_in() 
     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() 
     if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { 
      return false 
     } 
     let isReachable = flags.contains(.reachable) 
     let needsConnection = flags.contains(.connectionRequired) 
     return (isReachable && !needsConnection) 
    } 

    func showAlert() { 
     if !isInternetAvailable() { 
      let alert = UIAlertController(title: "Warning", message: "The Internet is not available", preferredStyle: .alert) 
      let action = UIAlertAction(title: "Dismiss", style: .default, handler: nil) 
      alert.addAction(action) 
      present(alert, animated: true, completion: nil) 
     } 
    } 

您需要导入:

import Foundation 
import SystemConfiguration 
+0

我把这段代码放在我的viewcontroller.swift中 – GoGode

+0

你可以从'viewDidLoad()'fort_t调用'showAlert()' esting。 – Lawliet

+0

但是我在哪里可以放回你回答的代码 – GoGode

相关问题