Skip to content

Instantly share code, notes, and snippets.

@gee1k
Created March 19, 2023 14:06
Show Gist options
  • Save gee1k/809a59bb47e51d8d3c2b3ce3612a3c24 to your computer and use it in GitHub Desktop.
Save gee1k/809a59bb47e51d8d3c2b3ce3612a3c24 to your computer and use it in GitHub Desktop.
iOS14 Local Network
import Foundation
import Network
public class Utils {
static func requestLocalNetworkAuthorization(_ timeout: Int = 1, completion: @escaping (_ granted: Bool) -> Void) {
let ipv4 = getIPv4Address() ?? "127.0.0.1"
var ipArr = ipv4.split(separator: ".")
ipArr[ipArr.count - 1] = "1"
let routerIp = ipArr.joined(separator: ".")
let ip = IPv4Address(routerIp) ?? .loopback
let queue = DispatchQueue(label: "Monitor")
let connection = NWConnection(host: .ipv4(ip), port: .http, using: .udp)
connection.start(queue: queue)
connection.stateUpdateHandler = { newState in
print(newState)
switch newState {
case .ready:
print("连接已准备就绪")
completion(true)
case .failed(let error):
print("连接失败:\(error.localizedDescription)")
completion(false)
case .cancelled:
print("连接超时取消")
completion(false)
default:
break
}
}
let timeout = DispatchTimeInterval.seconds(timeout)
let deadline = DispatchTime.now() + timeout
// Set timeout
DispatchQueue.main.asyncAfter(deadline: deadline) {
if connection.state == .waiting(.posix(.ENETDOWN)) || connection.state == .preparing {
print("Connection timed out.")
connection.cancel()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment