0

I had a well working method in Objective C to check wether the network connection to an IP address was available. The conversion to Swift has a problem.

The error is : Unmanaged'SCNetworkReachability' is not identical to 'SCNetworkReachability'

The compiler stops on the code line :

let success = SCNetworkReachabilityGetFlags(reachability, &flags)

I suppose I am overlooking something important!

Is this method the right way to check if a connection is alive and if host is available?

func hostReachable(ipadres:String) -> Bool {
    let host_name = ipadres.cStringUsingEncoding(NSASCIIStringEncoding)

    let reachability  = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, host_name!)
    var flags:SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable)
    let success = SCNetworkReachabilityGetFlags(reachability, &flags)

    let isAvailable = success && (flags | kSCNetworkFlagsReachable) && !(flags | kSCNetworkFlagsConnectionRequired)
    println("Reachability results---> \(success) \(host_name)', flags: \(flags)")

    if (isAvailable) {
        return true
    } else {
        println("'hostReachable:--> \(host_name) is not reachable")
        return false
    }
   return  false
}

After adding corrections the full working version is here.

func hostReachable(ipadres:String) -> Bool {
if let host_name = ipadres.cStringUsingEncoding(NSASCIIStringEncoding) {
    let reachability  = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, host_name).takeRetainedValue()
    var flags : SCNetworkReachabilityFlags = 0
    if SCNetworkReachabilityGetFlags(reachability, &flags) == 0 {
        return false
    }
    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection)
}else{
    return false
}
}

This method will check that the network correction is up or down, but unfortunately it will not check if the host or IP are really reachable. How could that be done? (for the moment I am using the Ping command with a NSTask).

Kader Mokhefi
  • 341
  • 4
  • 15
  • 1
    possible duplicate of [Working with C structs in Swift](http://stackoverflow.com/questions/25623272/working-with-c-structs-in-swift) – The title is horrible, but it is about the same problem, and the answer should contain what you need. – Martin R Oct 22 '14 at 16:35
  • Thanks Martin. The link helped find the problem. I added the full code as for now. – Kader Mokhefi Oct 22 '14 at 20:34

0 Answers0