Capture Wi-Fi network changing event in iOS

后端 未结 3 558
时光说笑
时光说笑 2020-12-15 10:50

Is there any way to capture the event occurs when a user connects to a particular WiFi network in iOS app. It is fine even if this can be achieved using any private library

相关标签:
3条回答
  • 2020-12-15 11:10

    I would recommend simply using what Larme posted, and setting up an NSTimer to check every second or so, what the SSID of your current network is, if you detect a change, simply do whatever you need to do. Keep in mind, changing WiFi networks is not something that happens instantaneously, so having a 1 second resolution is not bad

    In applicationDidFinishLoading

    NSTimer *ssidTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(fetchSSIDInfo) userInfo:nil repeats:YES];
    

    In AppDelegate

    - (id)fetchSSIDInfo {
         NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
         NSLog(@"Supported interfaces: %@", ifs);
         id info = nil;
         NSString *ifnam = @"";
         for (ifnam in ifs) {
             info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
             NSLog(@"%@ => %@", ifnam, info);
             if (info && [info count]) { break; }
         }
         if ([info count] >= 1 && [ifnam caseInsensitiveCompare:prevSSID] !=  NSOrderedSame) {
              // Trigger some event
              prevSSID = ifnam;
         }
    
         return info;
    }
    

    Something like that. I can not check if code is typo free as I am not in front of a mac, but it should not be too different

    0 讨论(0)
  • You want SystemConfiguration, which has facilities for seeing notifications on all sorts of networking changes. In particular you'll want to use SCDynamicStoreSetNotificationKeys to listen for changes to the devices and SCNetworkConfiguration to get information about the available interfaces.

    0 讨论(0)
  • 2020-12-15 11:20

    You can fetch details from your wifi connection:

    - (NSDictionary *)getConnectionDetails
    {
        NSDictionary *connectionDetails = [NSDictionary dictionary];
        CFArrayRef myArray = CNCopySupportedInterfaces();
        if (myArray) {
            CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
            connectionDetails = (__bridge_transfer NSDictionary*)myDict;
        }
        return connectionDetails;
    }
    

    And then if check [connectionDetails valueForKey:@"BSSID"] you will get BSSID.

    Also please note that you must to import #import <SystemConfiguration/CaptiveNetwork.h>

    0 讨论(0)
提交回复
热议问题