There are many reasons you need to check if the user is connected to the internet within your app, most important is that your app needs to retrieve data from a feed or display a web view. As soon as your app is loaded and before you make any calls to get data from a feed you should check if the user is connected to the internet.
In the past in Objective-C the most common way to check for connectivity is using Reachability, but it hasn’t been converted to Swift as of yet. Below is a simple way to add this feature to your new Swift project.
- Create a new Swift file within your project, name it “Reachability.swift”.
- Cut & paste the following code into it to create your class.
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(kCFAllocatorDefault, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .Reachable let needsConnection = flags == .ConnectionRequired return isReachable && !needsConnection } }
- You can check internet connection anywhere in your project using this code:
if Reachability.isConnectedToNetwork() == true { println("Internet connection OK") } else { println("Internet connection FAILED") }
- If the user is not connected to the internet, you may want to show them an alert dialog to notify them.
if Reachability.isConnectedToNetwork() == true { println("Internet connection OK") } else { println("Internet connection FAILED") var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK") alert.show() }
You can grab the full source code for this tutorial. Note: Built for Xcode 7.1.