Skip to content

Commit fc4436d

Browse files
committed
Local Network Authorization code
1 parent 33885be commit fc4436d

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import Foundation
2+
import Network
3+
4+
/// Uses bonjour networking to relialby check if user has granted local network access
5+
/// How to use:
6+
/// Add LocalNetworkAuthorization class to your project
7+
/// Open .plist file and add "_bonjour._tcp", "_lnp._tcp.", as a values under "Bonjour services"
8+
/// Call requestAuthorization() to trigger the prompt or get the authorization status if it already been approved/denied
9+
/// about the author: https://stackoverflow.com/a/67758105/705761
10+
public class LocalNetworkAuthorization: NSObject {
11+
private var browser: NWBrowser?
12+
private var netService: NetService?
13+
private var completion: ((Bool) -> Void)?
14+
15+
public func requestAuthorization() async -> Bool {
16+
return await withCheckedContinuation { continuation in
17+
requestAuthorization() { result in
18+
continuation.resume(returning: result)
19+
}
20+
}
21+
}
22+
23+
private func requestAuthorization(completion: @escaping (Bool) -> Void) {
24+
self.completion = completion
25+
26+
// Create parameters, and allow browsing over peer-to-peer link.
27+
let parameters = NWParameters()
28+
parameters.includePeerToPeer = true
29+
30+
// Browse for a custom service type.
31+
let browser = NWBrowser(for: .bonjour(type: "_bonjour._tcp", domain: nil), using: parameters)
32+
self.browser = browser
33+
browser.stateUpdateHandler = { newState in
34+
switch newState {
35+
case .failed(let error):
36+
print(error.localizedDescription)
37+
case .ready, .cancelled:
38+
break
39+
case let .waiting(error):
40+
print("Local network permission has been denied: \(error)")
41+
self.reset()
42+
self.completion?(false)
43+
default:
44+
break
45+
}
46+
}
47+
48+
self.netService = NetService(domain: "local.", type:"_lnp._tcp.", name: "LocalNetworkPrivacy", port: 1100)
49+
self.netService?.delegate = self
50+
51+
self.browser?.start(queue: .main)
52+
self.netService?.publish()
53+
}
54+
55+
56+
private func reset() {
57+
self.browser?.cancel()
58+
self.browser = nil
59+
self.netService?.stop()
60+
self.netService = nil
61+
}
62+
}
63+
64+
extension LocalNetworkAuthorization : NetServiceDelegate {
65+
public func netServiceDidPublish(_ sender: NetService) {
66+
self.reset()
67+
print("Local network permission has been granted")
68+
completion?(true)
69+
}
70+
}

0 commit comments

Comments
 (0)