Here I present some simple code to check if wifi is enabled on iOS, which could be used to alert the user if your application uses location services.

One of my most visited posts is from 3 years ago, which has some demo code for checking whether the internet is accessible from the device. The code presented here can detect if wifi is enabled, which is related, in a way.

Remember that devices could also access the internet via the cellular network, so this check can’t really be used as a precursor to the method used in the other article. On the other hand, if your application uses location services, then you could use this code to alert the user that your app may not be as accurate as it would otherwise be, and that they may want to turn the wifi back on.

Those who visited my last article may recognise this code, since it comes from the demo in that article. During the testing process, I had inadvertently left the wifi turned off (probably because the network I was connected to had poor performance), and had not turned it on later. When I was checking the location updates in the demo, I noticed they were not as reliable as before.

I remembered that other “built-in” iOS apps themselves sometimes warn that location updates may be more reliable if wifi is turned on, so I set about finding how to determine if it is. I came across the article listed in the code below, translated it into Delphi, and voila!

Here’s the code:

[sourcecode language=”delphi”]

uses
System.SysUtils, Posix.Base, Posix.NetIf, Macapi.ObjCRuntime, Macapi.ObjectiveC, Macapi.Helpers, iOSapi.Foundation;

const
cWifiInterfaceName = ‘awdl0’; // That’s a small L (l), not a one (1)

function getifaddrs(var ifap: pifaddrs): Integer; cdecl; external libc name _PU + ‘getifaddrs’;
procedure freeifaddrs(ifap: pifaddrs); cdecl; external libc name _PU + ‘freeifaddrs’;

function StrToNSStringPtr(const AValue: string): Pointer;
begin
Result := (StrToNSStr(AValue) as ILocalObject).GetObjectID;
end;

// Translated from here: http://www.enigmaticape.com/blog/determine-wifi-enabled-ios-one-weird-trick
function IsWifiEnabled: Boolean;
var
LAddrList, LAddrInfo: pifaddrs;
LSet: NSCountedSet;
begin
Result := False;
if getifaddrs(LAddrList) = 0 then
try
LSet := TNSCountedSet.Create;
LAddrInfo := LAddrList;
repeat
if (LAddrInfo.ifa_flags and IFF_UP) = IFF_UP then
LSet.addObject(TNSString.OCClass.stringWithUTF8String(LAddrInfo.ifa_name));
LAddrInfo := LAddrInfo^.ifa_next;
until LAddrInfo = nil;
Result := LSet.countForObject(StrToNSStringPtr(cWifiInterfaceName)) > 1;
finally
freeifaddrs(LAddrList);
end;
end;

[/sourcecode]