-1

I know that a lot of people may have asked quite the same question, but what I would like to do is a little different. I would like to know how can check if the internet is on, while pressing a button. When the user press the button, if he isn't connect to the internet the next page won't show up. A message would appear demanding him to connect the internet. Than if he is connect to the internet, when he clicks the button the page would change normally. Anybody knows how I can do this? Thanks!

dp6000
  • 473
  • 5
  • 15
  • See [check internet connection in cocoa application](http://stackoverflow.com/questions/2995822/check-internet-connection-in-cocoa-application). – zneak Apr 17 '15 at 14:59
  • I would like the code in swift, cause I don't know very well Objective-C – dp6000 Apr 17 '15 at 15:11
  • 1
    I think you should try to do it on your own. There are at most 6 important lines in this function and the Swift equivalent code will be almost identical. – zneak Apr 17 '15 at 15:16
  • possible duplicate http://stackoverflow.com/questions/25398664/check-for-internet-connection-availability-in-swift – Victor Sigler Apr 17 '15 at 16:20

1 Answers1

0

Use this class, call isConnectedToNetwork() when the button is pressed (I'm assuming you know how to use @IBAction). If it returns true let the user know in which ever way you want that there is interwebs.

import Foundation
import SystemConfiguration

enum ReachabilityType {
    case WWAN,
    WiFi,
    NotConnected
}

public class Connected {
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
}
}

I got this code from somewhere on the internet I don't think this is the exact project I got it from but It seems this guy possibly made it from the same source. https://github.com/Isuru-Nanayakkara/IJReachability/blob/master/IJReachability/IJReachability/IJReachability.swift

Also there is the apple Reachability obj-c files you can use and just use a header.

boidkan
  • 4,691
  • 5
  • 29
  • 43