检查互联网连接是否可用迅速

是否有一个苹果框架包检测是否有互联网连接? 目前我的应用程序崩溃,当它试图地理位置没有互联网连接的用户的位置。

/*inside locationManager didUpdateLocations method*/ var currentLocation:CLLocation? = locations[0] as? CLLocation geocoder = CLGeocoder() //Crashes on line below when there isn't an internet connection //Need to add function to check if internet connection is live //Before running reverseGeocodeLocation geocoder.reverseGeocodeLocation (currentLocation,handleGeocode) 

我对swift和ios编程有点新东西 – 我的歉意。

不是一个完整的networking检查库,但我发现这个检查networking可用性的简单方法。 我设法把它翻译成Swift和这里的最终代码。

 import Foundation import SystemConfiguration 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(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) ? true : false } } 

它适用于3G和WiFi连接。 我也通过一个实例将它上传到我的Github 。 如果您正在寻找一种简单的方法来纯粹在Swift中检查networking可用性,则可以使用它。

使用Babatunde的代码示例,但这里是Swift 2.0和error handling的更新版本:编辑:也更改为iOS的HTTPS的谷歌的URL 9.编辑2:原始文章: http ://www.brianjcoleman.com/tutorial-check- 换因特网连接在-斯威夫特/

 import Foundation import SystemConfiguration public class Reachability { // Check if internet connection is available class func isConnectedToNetwork() -> Bool { var status:Bool = false let url = NSURL(string: "https://google.com") let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "HEAD" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 10.0 var response:NSURLResponse? do { let _ = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData? } catch let error as NSError { print(error.localizedDescription) } if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode == 200 { status = true } } return status } } 

由于Reachability还没有完全移植到,所以您可以使用下面的示例代码来检查Internet连接:

 public class Reachability { /** * Check if internet connection is available */ class func isConnectedToNetwork() -> Bool { var status:Bool = false let url = NSURL(string: "http://google.com") let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "HEAD" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 10.0 var response:NSURLResponse? var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData? if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode == 200 { status = true } } return status } } 

请参阅以下function的示例用法:

 // Check if internet is available before proceeding further if Reachability.isConnectedToNetwork() { // Go ahead and fetch your data from the internet // ... } else { println("Internet connection not available") var alert = UIAlertView(title: "No Internet connection", message: "Please ensure you are connected to the Internet", delegate: nil, cancelButtonTitle: "OK") alert.show() }