Hyperconnectivity icon indicating copy to clipboard operation
Hyperconnectivity copied to clipboard

Usage quickly after app launch or quickly in a sharing extension.

Open crspybits opened this issue 5 years ago • 2 comments

Thanks for this package! I'm trying to make use of it to detect if there is a network available in a sharing extension-- quickly after it starts. It's consistently just indicating there is no network connection. But, there is one. Is this expected behavior? Any thoughts?

I also see this behavior, but less consistently, when the app first launches-- and I quickly use this to detect network availability. It will at times incorrectly indicate the network is not available.

crspybits avatar Mar 06 '21 04:03 crspybits

Let me correct that. It's just not giving me an initial value early into the app launch. It's not that it's indicating that the network is not available.

crspybits avatar Mar 06 '21 04:03 crspybits

Dear distant-past user @crspybits I just had this exact same issue. I ended up using withTaskCancellationHandler to resolve this race condition. Here is a playground file to get you started - although I assume you're probably finished, published and subsetted this project by now

var stashedContinuations = [CheckedContinuation<Bool, Error>]()
var latestResult: ConnectivityResult?

private struct Continuation: Identifiable {
  let id = UUID()
  let continuation: CheckedContinuation<Bool, Error>
}

func hasInternetConnectivity() async throws -> Bool {
  
  if let latestResult = latestResult {
    return latestResult.isConnected
  }
  
  return try await withTaskCancellationHandler(
    handler: {
      cancelStashedContinuations()
    },
    operation: {
      try await withCheckedThrowingContinuation { continuation in
        stashedContinuations.append(.init(continuation: continuation))
      }
    })
}

func continueAllContinuations() {
  
  stashedContinuations.forEach {
    $0.continuation.resume(returning: latestResult?.isConnected == true)
    print(">> responding to a continuation!")
  }
  
  stashedContinuations.removeAll()
  
}

func cancelStashedContinuations() {
  stashedContinuations.forEach({ $0.continuation.resume(returning: false) })
  stashedContinuations.removeAll()
}

Task {
  print("blah")
  
  DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    continueAllContinuations()
  }
  let conn = try? await hasInternetConnectivity()
  print(conn)
}

That was my draft POC (still need to thoroughly test when implemented). Hopefully its useful for future folk

mylogon341 avatar Jan 13 '22 16:01 mylogon341