How Swift Gets the Name of MacOS Network Environment

Asked 2 years ago, Updated 2 years ago, 47 views

Swift is creating an app that runs on macOS.

I would like to obtain the name of the currently selected Network Environment, which is the red border part shown in the image 1.

The SSID retrieval was successful with the following code:

import CoreWLAN

let SSID_Name: String = {
    US>"return CWWiFiClient() ?.interface(withName:nil) ?.ssid()"
}()

I tried using the above code, but I didn't understand it.

I can't find that kind of information even when I search online.
If there is any way, please let me know.
Thank you for your cooperation.

I want to get a name for my network environment

swift xcode macos

2022-09-30 18:16

1 Answers

The actual information seems to be here.

/Library/Preferences/SystemConfiguration/preferences.plist

If you look into SystemConfiguration, you'll find some official Apple documents.

System Configuration Programming Guidelines

API Reference SystemConfiguration

SCNetworkConfiguration

In the preferences.plist, Sets was the actual data, so it looks suspicious around here.

Configuring Network Sets

func SCNetworkSetCopyAll(SCPreferences)
Returns all available sets for the specified preferences session.

After trying other API functions through trial and error, I was able to get the name of my Mac (10.11.5) network environment (Location:) with this code.

import Foundation
import SystemConfiguration

// Obtain Default System Settings (SCPreferences)
let prefs = SCPreferencesCreate(nil, "process-name" as CFSstring, nil)!
// Obtain SCNetworkSet from System Configuration
iflet sets = SCNetworkSetCopyAll(prefs) as ? [SCNetworkSet] {
    for set in sets {
        // Obtain a user-defined name from SCNetworkSet
        let userDefinedName = SCNetworkSetGetName(set) as String?
        print(userDefinedName???"*no name*")
    }
} else{
    print("cannot get [SCNetworkSet] from this preference:\(prefs)")
}

I haven't even tried what happens in SandBox environments, but for your information.


2022-09-30 18:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.