2017年8月21日 星期一

[iOS] 取得附近 Wi-Fi SSID 清單

在 stackoverflow 上大部分都是很久以前發問的,大家的回應都是
  1. 只能拿到當前連線 Wi-Fi 資訊
  2. 使用 private API

最後終於找到在 iOS 9 可以使用 NEHotspotHelper,但有一些限制:
  1. iOS 9+ 支援
  2. 需要向 Apple 申請 com.apple.developer.networking.HotspotHelper entitlement 才可使用
  3. 只能被動由系統通知 Wi-Fi 清單,無法主動取得

大概寫一下流程,希望有空的時候可以補齊
前置步驟比較瑣碎
  1. 首先到 https://developer.apple.com/contact/network-extension 填寫申請書
  2. 在開發者網頁中,將 App ID 啟用 Network Extensions
  3. 更新 Provisioning Profiles,並且選擇使用 Network Extension iOS Entilements
  4. XCode 更新 Provisioning Profiles
  5. Info.plist 檔案中在 UIBackgroundModes 加入 network-authentication
  6. entitlements 檔案中加入 com.apple.developer.networking.HotspotHelper 為 YES
程式碼:

NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:@"xxx" forKey:kNEHotspotHelperOptionDisplayName];
dispatch_queue_t queue = dispatch_queue_create("xxx", 0);

BOOL ret = [NEHotspotHelper registerWithOptions:options queue:queue handler:^(NEHotspotHelperCommand *cmd) {
    NEHotspotNetwork *network;
    if (cmd.commandType == kNEHotspotHelperCommandTypeFilterScanList) {
        for (network in cmd.networkList) {
            NSString *wifiInfo = [[NSString alloc] initWithFormat:@"SSID: [%@] MAC: [%@] strength: [%f]", network.SSID, network.BSSID, network.signalStrength];
            NSLog(@"%@", wifiInfo);
        }
    }
}];
NSLog(@"return value %d", ret);

確認 ret 為 True 表示有註冊成功,可到設定 -> Wi-Fi,觸發 Wi-Fi 清單更新後就會印 Log 到 console 上了。

參考資料