Swift: How to check if my app has WLAN permission

2019-02-18 09:50发布

问题:

I'm developing an app in which I need to know:

  1. Does my app has the permission to access WLAN network.
  2. Is the device currently connected to a WIFI.

I know you can use Reachability to check if the device is connected to the internet, but it return true even if the app doesn't has the permission to access network. How can I know the 2 information I listed above ?

Additional information: This is not a regular app. This app is used to control a toy via WIFI. So I don't really care if the app is connected to the internet. All I want to know is if the app has the permission to access WLAN network.

回答1:

If you are worried that there may be a captive portal giving a false "connected" status to Reachability then you need to attempt to retrieve a known piece of data from a known website; then if you get the expected result you can be fairly confident that your app has network access.

For example, http://captive.apple.com returns:

<HTML>
  <HEAD>
   <TITLE>Success</TITLE>
  </HEAD>
  <BODY>
     Success
  </BODY>
</HTML>

This is the web site that iOS and macOS attempt to access in order to determine whether the hotspot login helper window should be shown.

If iOS doesn't get the expected "success" (as is the case if all access is redirected to a "login" screen) or the connection times out then the helper window is shown.