轉載:https://majing.io/posts/10000049911218
iOS 申請獲取 Wifi 列表權限
iOS 上獲取 Wifi 列表其實也有很大限制,在 iOS 9 以前是不能獲取Wifi列表的,只能獲取當前連接的 Wifi 信息,也就表示只有連接了 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列表回調
1、向 Apple 申請開發 Network Extension 權限
首先要先寫封郵件給 networkextension@apple.com ,問蘋果要開發 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.
。。。。
2、申請包含 Network Extension 的描述文件
選擇包含 Network Extension 的描述文件,后點擊下載,下載完成雙擊描述文件。
3、配置 Info.plist
Xcode Info.plist 里 Required background modes 添加 一個 network-authentication(item)
4、配置 entitlements
Demo.entitlements(Demo是項目名稱) 里添加 Key-Value: com.apple.developer.networking.HotspotHelper -> YES
[圖片上傳中...(image-bd7f52-1609926532897-2)]
5、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是否為網絡的所選助手
6、獲取Wifi列表回調
當你把上面的代碼寫完,并成功運行項目后,發現并沒有Wifi列表的回調。因為你還沒刷新Wifi列表,你需要:
- 打開手機系統設置 -> WLAN -> 系統 Wifi 列表加載出來時,上面代碼部分才會回調,才能獲取到 Wifi 列表。
[圖片上傳中...(image-a06afb-1609926532896-1)]
這個時候你就能看到控制臺源源不斷的Log。
注意事項
- 1、獲取Wifi列表功能由于是需要申請后臺權限,所以能后臺激活App(應用程序),而且激活后App的進程能存活幾個小時。
- 2、整個獲取Wifi列表不需要App用戶授權,也就是在App用戶無感知下獲取設備的Wifi列表信息,使用時請正當使用。
- 3、Wifi列表獲取 NetworkExtension 是 iOS 9以后才出的,目前 iOS 9 已經覆蓋很廣了。
下面付一張來自 TalkingData 對iOS操作系統的統計報表,時間:2017-01-03
[圖片上傳中...(image-481307-1609926532896-0)]