LoginSignup
21
20

More than 3 years have passed since last update.

[iOS13]接続中のWi-FiのSSIDを取得するCNCopyCurrentNetworkInfo()がnilになった?

Last updated at Posted at 2019-06-13

iOS12までSSIDを取得する方法

Stack Overflowから参照。

import Foundation
import SystemConfiguration.CaptiveNetwork

func getSSID() -> String? {
    var ssid: String?
    if let interfaces = CNCopySupportedInterfaces() as NSArray? {
        for interface in interfaces {
            if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
                ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                break
            }
        }
    }
    return ssid
}

iOS12以降、Capablitiesで Access Wifi Information を追加する必要があります。
参考記事:iOS12以降でCNCopyCurrentNetworkInfo() の注意点

iOS13はどうなった?

CNCopyCurrentNetworkInfo()nilになりました。

Apple Developer ForumsにCNCopyCurrentNetworkInfo()が使えない報告があります。

原因

Wi-Fi情報からユーザーの位置を推測できます。Appleがユーザーのプライバシーを守るため、iOS13以降、CNCopyCurrentNetworkInfo()でSSIDなどの情報を取得するには、位置情報の使用許可が必要になりました。

WWDC19 Session 713: Advances in Networking, Part 2から抜粋。

Now you all know the important privacy to Apple. And one of the things we realized. Is that... Accessing Wi-Fi information can be used to infer location.
So starting now, to access that Wi-Fi information. You'll need the same kind of privileges that you'll need to get other location information.

対処法

位置情報を取得する許可をリクエストします。

参考記事:【CoreLocation】位置情報を取得する

CoreLocationフレームワークをインポートします。

import CoreLocation

iOS13であれば、位置情報の許可をリクエストします(ここで「使用中のみ許可」)。
すでに許可された場合又はiOS12までの場合はupdateWiFi()を呼び出します。

if #available(iOS 13.0, *) {
    let status = CLLocationManager.authorizationStatus()
    if status == .authorizedWhenInUse {
        updateWiFi()
    } else {
        locationManager.requestWhenInUseAuthorization()
    }
} else {
    updateWiFi()
}

ユーザーが許可した場合は、updateWiFi()メッソドを呼び出します。

class ViewController: UIViewController, CLLocationManagerDelegate {
    ...
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            updateWiFi()
        }
    }
    ...
}

メソッドupdateWiFi()の中身

func updateWiFi() {
    print("SSID: \(getSSID())")
    ssidLabel.text = getSSID()
}

サンプルプロジェクト

iOS13-WiFi-Info

アプリをアップデートする

この対策法は新しいAPIを使用していないため、Xcode 11 GM版を待つ必要はありません。
Xcode 10で今すぐ不具合を修正しましょう。

追記

iOS 13.0から13.2までの端末が位置情報を取得できても、CNCopyCurrentNetworkInfo()nilになって使えない報告がたくさんありました。
iOS 13.3 beta 1 (17C5032d)に修正されたそうです。アップデートしてお試しください。
関連 GitHub コメント:
https://github.com/HackingGate/iOS13-WiFi-Info/issues/7#issuecomment-550164579

21
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
20