Search code examples
swiftfunctionreachabilitybackground-thread

Waiting for a background thread to complete before function return


I try to create function that return Internet status as Bool:

func isConnectedToNetwork()->Bool{
    var InternetStatus = Bool()
    RealReachability.sharedInstance().reachabilityWithBlock { (status:ReachabilityStatus) in
        switch status {
        case .RealStatusNotReachable:
            InternetStatus = false
        default:
            InternetStatus = true

        }
    }
   return InternetStatus
}

But I have a problem, RealReachability.sharedInstance().reachabilityWithBlock {} works in background thread, and function return before background thread complete.

How to wait background thread result before function return?


Solution

  • Don't wait, tell.

    Use a completion handler which is called when the asynchronous task has been completed

    func isConnectedToNetwork(completion:(Bool -> Void)) {
        RealReachability.sharedInstance().reachabilityWithBlock { (status:ReachabilityStatus) in
            switch status {
            case .RealStatusNotReachable:
                completion(false)
            default:
                completion(true)
            }
        }
    }
    

    and call it

    isConnectedToNetwork { success in
      print(success)
      // do something with the success value
    }