Browse Source

Throws updates

Throwing methods no longer return nil.
init(hostname: String) now throws
Ashley Mills 10 years ago
parent
commit
0bf755e4bd

+ 1 - 1
Reachability Sample/Reachability Sample/ViewController.swift

@@ -20,7 +20,7 @@ class ViewController: UIViewController {
         super.viewDidLoad()
 
         do {
-            guard let reachability = try Reachability.reachabilityForInternetConnection() else { return }
+            let reachability = try Reachability.reachabilityForInternetConnection()
             self.reachability = reachability
         } catch ReachabilityError.FailedToCreateWithAddress(let address) {
             networkStatus.textColor = UIColor.redColor()

+ 5 - 4
Reachability.swift

@@ -30,6 +30,7 @@ import Foundation
 
 enum ReachabilityError: ErrorType {
     case FailedToCreateWithAddress(sockaddr_in)
+    case FailedToCreateWithHostname(String)
     case UnableToSetCallback
     case UnableToSetDispatchQueue
 }
@@ -97,15 +98,15 @@ public class Reachability: NSObject {
         self.reachabilityRef = reachabilityRef
     }
     
-    public convenience init?(hostname: String) {
+    public convenience init(hostname: String) throws {
         
         let nodename = (hostname as NSString).UTF8String
-        guard let ref = SCNetworkReachabilityCreateWithName(nil, nodename) else { return nil }
+        guard let ref = SCNetworkReachabilityCreateWithName(nil, nodename) else { throw ReachabilityError.FailedToCreateWithHostname(hostname) }
 
         self.init(reachabilityRef: ref)
     }
 
-    public class func reachabilityForInternetConnection() throws -> Reachability? {
+    public class func reachabilityForInternetConnection() throws -> Reachability {
         
         var zeroAddress = sockaddr_in()
         zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
@@ -118,7 +119,7 @@ public class Reachability: NSObject {
         return Reachability(reachabilityRef: ref)
     }
 
-    public class func reachabilityForLocalWiFi() throws -> Reachability? {
+    public class func reachabilityForLocalWiFi() throws -> Reachability {
 
         var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
         localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress))