Reputation: 4501
In iOS 16 is a way to check if user has granted local network access permission?
In iOS 15 and before, there is no accurate way to do it. How is iOS 16 now? Any new ways or more accurate way to do it?
https://developer.apple.com/forums/thread/681971
Upvotes: 1
Views: 1413
Reputation: 256
In iOS 16, Apple introduced a new way to check if the user has granted local network access permission. You can use the Network.framework to create a connection to a local network service and then check the status of the connection.
Here's how you can do it:
Import Network Framework: Make sure to import the Network framework in your project.
Create and Start a Connection: Create a connection to a local network service and start it. This will trigger the local network access prompt if it hasn't already been shown.
Handle Connection States: The stateUpdateHandler will help you determine if the connection is ready, failed, or waiting. If the connection fails or is waiting, you can inspect the error to see if it's related to local network access permission.
Here's a complete example:
import Network
func checkLocalNetworkAccess() {
let connection = NWConnection(host: "example.local", port: 12345, using: .tcp)
connection.stateUpdateHandler = { newState in
switch newState {
case .ready:
print("Local network access granted")
case .failed(let error):
if let nwError = error as? NWError, nwError == .posix(.ehostdown) {
print("Local network access not granted")
} else {
print("Connection failed with error: \(error)")
}
case .waiting(let error):
if let nwError = error as? NWError, nwError == .posix(.ehostdown) {
print("Local network access not granted")
} else {
print("Connection waiting with error: \(error)")
}
default:
break
}
}
connection.start(queue: .main)
}
Note that you need to replace "example.local" and 12345 with appropriate values for your local network service.
This approach will help you determine if the user has granted local network access permission in iOS 16 and later.
Upvotes: 0