iOS Wifi 列表獲取

iOS 上獲取 Wifi 列表其實有很大限制,在 iOS 9 以前是不能獲取Wifi列表的,只能獲取當前連接的 Wifi 信息,也就表示只有連接了 Wifi 才能確定位置。
Apple 在 iOS 9 以後,提供了獲取Wifi列表的API,但是獲取Wifi列表是有門檻的,主要步驟有:


  1. 向 Apple 申請開發 Network Extension 權限
  2. 申請包含 Network Extension 的描述文件
  3. 配置 Info.plist
  4. 配置 entitlements
  5. iOS 獲取 Wifi 列表代碼實現
  6. 獲取Wifi列表回調

向 Apple 申請開發 Network Extension 權限

首先要先寫封郵件給 [email protected] ,問蘋果要開發 Network Extension 的權限。 蘋果收到郵件後會自動回覆郵件,在 https://developer.apple.com/contact/network-extension/ 裏面填寫申請表格,內容包括:

Organization:               

Company / Product URL:             

What's your product's target market?              

What's your company's primary function?             

Describe your application and how it will use the Network Extension framework.            

What type of entitlement are you requesting?                     

...

申請後大概兩週左右能收到 Aplle的 確認信,如:

Hi, 

Thanks for your interest in the Network Extension APIs.

We added a new template containing the Network Extension entitlements to your team.

......

申請包含 Network Extension 的描述文件

選擇包含 Network Extension 的描述文件,後點擊下載,下載完成雙擊描述文件。

xcode中開啓Network Extensions權限

在這裏插入圖片描述

配置 entitlements

xxx.entitlements(xxx是項目名稱) 裏添加 Key-Value: com.apple.developer.networking.HotspotHelper -> YES,沒有此文件需要先創建一個:
在這裏插入圖片描述

iOS 獲取 Wifi 列表代碼實現

#import <NetworkExtension/NetworkExtension.h>
- (void)getWifiList {

    if (![[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {return;}
    dispatch_queue_t queue = dispatch_queue_create("com.leopardpan.HotspotHelper", 0);
    [NEHotspotHelper registerWithOptions:nil queue:queue handler: ^(NEHotspotHelperCommand * cmd) {
        if(cmd.commandType == kNEHotspotHelperCommandTypeFilterScanList) {
            for (NEHotspotNetwork* network  in cmd.networkList) {
                NSLog(@"network.SSID = %@",network.SSID);
            }
        }
    }];
}

kNEHotspotHelperCommandTypeFilterScanList: 表示掃描到 Wifi 列表信息。

NEHotspotNetwork 裏有如下信息


SSID:Wifi 名稱
BSSID:站點的 MAC 地址
signalStrength: Wifi信號強度,該值在0.0-1.0之間
secure:網絡是否安全 (不需要密碼的 Wifi,該值爲 false)
autoJoined: 設備是否自動連接該 Wifi,目前測試自動連接以前連過的 Wifi 的也爲 false 。
justJoined:網絡是否剛剛加入
chosenHelper:HotspotHelper是否爲網絡的所選助手


獲取Wifi列表回調

當你把上面的代碼寫完,併成功運行項目後,發現並沒有Wifi列表的回調。因爲你還沒刷新Wifi列表,你需要:

打開手機系統設置 -> WLAN -> 系統 Wifi 列表加載出來時,上面代碼部分纔會回調,才能獲取到 Wifi 列表。
這個時候你就能看到控制檯源源不斷的Log。

注意事項

1、獲取Wifi列表功能由於是需要申請後臺權限,所以能後臺激活App(應用程序),而且激活後App的進程能存活幾個小時。
2、整個獲取Wifi列表不需要App用戶授權,也就是在App用戶無感知下獲取設備的Wifi列表信息,使用時請正當使用。
3、Wifi列表獲取 NetworkExtension 是 iOS 9以後纔出的,目前 iOS 9 已經覆蓋很廣了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章