1

I have the following function. It runs in ViewDidLoad(). I am trying to add some error handling to an iPhone app for non-connectivity. Essentially, I want the program to check if the URLrequest can connect to its target URL and print the appropriate text to the console.

I have found some previous questions that address the problem in obj C, but I can't find any good info for how to do it in Swift. Any help?

func loadURL(){
        let requestURL = NSURL(string: path)
        let request = NSURLRequest(URL: requestURL!)
        if(/* ??? */){
            webViewer.loadRequest(request)
            println("Good connection")
        }
        else{
            println("No connection")
        }
    }
mstagg
  • 507
  • 4
  • 16

5 Answers5

2

There are various pointers in the right direction here (particularly David's), but the key to understand is that it is impossible to confirm connectivity to a service without actually performing a request and getting a response (and even that doesn't promise that your next request will succeed). So the correct answer is to just perform the request asynchronously and deal with the result or error. Do not attempt to detect connectivity and then load the request. Just load the request. If you're not connected, you'll get an error.

The answer from user2509601 is useful, but it only tells you that the device would try to make the request. It doesn't tell you that the request would succeed. So it can provide a negative (it's not even worth trying), but it can't actually tell you that you're connected. In most cases, checking reachability is a waste of time; you might as well just try to make the request. (Reachability is mostly useful to help you decide when next to try the request.)

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • I guess that raises the question of error handling in swift. Further down the rabbit hole I go... – mstagg Feb 10 '15 at 22:03
  • I agree. It's better to send a request and then handle the error appropriately instead of checking first for connectivity. – iCode Feb 11 '15 at 10:37
0

It is possible to check for internet connection availability:

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
    }

}

taken from here: Check for internet connection availability in Swift

Community
  • 1
  • 1
iCode
  • 1,456
  • 1
  • 15
  • 26
0

What I'm using to check the connection:

 let request = NSURLRequest(URL: NSURL(string: yourURL)!)

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response, data, error) -> Void in
     if data == nil {
         println("Connection error")
         return
     }
     else {
         println("Connection successful")
     }
    )}

You can also send a Synchronous request.

Dejan Skledar
  • 11,280
  • 7
  • 44
  • 70
0

Presumably webViewer is an instance of UIWebView

The appropriate way to handle connectivity failures in conjunction with a UIWebView is by the delegate methods.

class FooViewController : UIViewController, UIWebViewDelegate {
    var webViewer : UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webViewer.delegate = self       // better yet, set this in the storyboard
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        // Handle a failure to load the url here
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        // Handle successful load here
    }
}
David Berry
  • 40,941
  • 12
  • 84
  • 95
-1

In the interest of not writing more code than you have to, I'd recommend checking out an open source component to solve this problem. Mattt Thompson ported his excellent AFNetworking library to Swift as Alamofire, which contains (among many other very useful things) the AFNetworkReachabilityManager, which is useful for determining network availability.

oltman
  • 1,772
  • 1
  • 14
  • 24