iOS开发——网络编程Swift篇&(一)网络监测

网络监测

 enum ReachabilityType {
     case WWAN,
     WiFi,
     NotConnected
 }

 public class Reachability {

     /**
     :see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/
     */
     class func isConnectedToNetwork() -> Bool {

         var zeroAddress = sockaddr_in(sin_len: , sin_family: , sin_port: , sin_addr: in_addr(s_addr: ), sin_zero: (, , , , , , , ))
         zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
         zeroAddress.sin_family = sa_family_t(AF_INET)

         let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
             SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($)).takeRetainedValue()
         }

         var flags: SCNetworkReachabilityFlags =
          {
             return false
         }

         let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) !=
         let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 

         return (isReachable && !needsConnection) ? true : false
     }

     class func isConnectedToNetworkOfType() -> ReachabilityType {

         var zeroAddress = sockaddr_in(sin_len: , sin_family: , sin_port: , sin_addr: in_addr(s_addr: ), sin_zero: (, , , , , , , ))
         zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
         zeroAddress.sin_family = sa_family_t(AF_INET)

         let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
             SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($)).takeRetainedValue()
         }

         var flags: SCNetworkReachabilityFlags =
          {
             return .NotConnected
         }

         let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) !=
         let isWWAN = (flags & UInt32(kSCNetworkReachabilityFlagsIsWWAN)) !=
         //let isWifI = (flags & UInt32(kSCNetworkReachabilityFlagsReachable)) != 0

         if(isReachable && isWWAN){
             return .WWAN
         }
         if(isReachable && !isWWAN){
             return .WiFi
         }

         return .NotConnected
         //let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

         //return (isReachable && !needsConnection) ? true : false
     }

使用:

     // MARK: - 检测网络连接情况
     @IBOutlet var statusLabel: UILabel!
     @IBOutlet var typeLabel: UILabel!

     @IBAction func checkButtonUpinside(sender: UIButton) {

         if Reachability.isConnectedToNetwork() {
             statusLabel.text = "网络连接:可用"
         } else {
             statusLabel.text = "网络连接:不可用"
         }

         let statusType = Reachability.isConnectedToNetworkOfType()
         switch statusType{
         case .WWAN:
             typeLabel.text = "连接类型:移动网络"
         case .WiFi:
             typeLabel.text = "连接类型:WiFi"

         case .NotConnected:
             typeLabel.text = "连接类型:没有网络连接"
         }
     }
 
 
上一篇:Android 获取keystore SHA1方法


下一篇:Hadoop(四)HDFS的高级API操作