How do I get current network location name? - cocoa

In system network preference there are some location names.How to get the current or active network location name and list of all network locations? I guess SystemConfiguration.framework supports this but i didn't get exactly which API to use.Thanks in advance for your answer. RegardsDevara Gudda

You can use SCPreferencesCreate to get the preferences, then SCNetworkSetCopyAll to get just the network locations. SCNetworkSetGetName will get the name of a location.
SCPreferencesRef prefs = SCPreferencesCreate(NULL, #"SystemConfiguration", NULL);
NSArray *locations = (NSArray *)SCNetworkSetCopyAll(prefs);
for (id item in locations) {
NSString *name = (NSString *)SCNetworkSetGetName((SCNetworkSetRef)item);
...
}
CFRelease(locations);
CFRelease(prefs);
Read "System Configuration Programming Guidelines" for more.

This is a swift 5.1 implementation to get list of all available network location
func getAvailabeNetworkLocation() -> [String]
{
var results = [String]()
var prefs : SCPreferences
prefs = SCPreferencesCreate (nil, "Softech" as CFString, nil)!
var sets : CFArray
sets = SCNetworkSetCopyAll (prefs)!
let count = CFArrayGetCount(sets) as Int
var newSet : SCNetworkSet? = nil
var bFound : Bool = false
for nIndex in 0..<count {
let mySet = CFArrayGetValueAtIndex (sets, nIndex)
let key = Unmanaged<SCNetworkSet>.fromOpaque(mySet!)
newSet = key.takeUnretainedValue()
let name : String = SCNetworkSetGetName(newSet!)! as String
print("Network location name: \(name)")
results.append(name)
}
return results
}

Related

Get mounted volumes list with Swift?

Does anyone know how to get a list of all removable volumes mounted with Swift?
I've already tried this, but it return a list of all files and subfolders of external drivers:
let filemanager:NSFileManager = NSFileManager()
let files = filemanager.enumeratorAtPath("/Volumes")
while let file = files?.nextObject() {
println(file)
menu.addItem(NSMenuItem(title: file as! String, action: Selector(""), keyEquivalent: ""))
}
This prints the list of all mounted volumes:
let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)
if let urls = paths as? [NSURL] {
for url in urls {
println(url)
}
}
You can of course filter to get only the paths inside the "Volumes" directory:
let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)
if let urls = paths as? [NSURL] {
for url in urls {
if url.relativePath?.pathComponents.count > 1 {
if url.relativePath?.pathComponents[1] == "Volumes" {
println(url)
}
}
}
}
And with Swift 2 there's two differences: pass [] instead of nil for the filemanager's options, and there's no need to cast the array of NSURLs:
let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: [])
if let urls = paths {
for url in urls {
if url.relativePath?.pathComponents.count > 1 {
if url.relativePath?.pathComponents[1] == "Volumes" {
print(url)
}
}
}
}
Update for Swift 2.1
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = NSFileManager().mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: [])
if let urls = paths {
for url in urls {
if let components = url.pathComponents
where components.count > 1
&& components[1] == "Volumes" {
print(url)
}
}
}
Update for Swift 3
let keys: [URLResourceKey] = [.volumeNameKey, .volumeIsRemovableKey, .volumeIsEjectableKey]
let paths = FileManager().mountedVolumeURLs(includingResourceValuesForKeys: keys, options: [])
if let urls = paths {
for url in urls {
let components = url.pathComponents
if components.count > 1
&& components[1] == "Volumes"
{
print(url)
}
}
}
On Unix systems a filesystem object with a system file number of 2 is a mount, regardless of a remote (nfs, smb, afp) or a local mount.
Here's an example:
let path = "/System/Volumes/Preboot"
let systemAttributes = try FileManager.default.attributesOfItem(atPath: String(describing: path))
if let fileSystemFileNumber = systemAttributes[.systemFileNumber] as? NSNumber {
print("System File Number: \(fileSystemFileNumber)")
}
So maybe this could be a short way to find mounts
let keys: [URLResourceKey] = [
.volumeNameKey,
.volumeIsRemovableKey,
.volumeIsEjectableKey,
.volumeAvailableCapacityKey,
.volumeTotalCapacityKey,
.volumeUUIDStringKey,
.volumeIsBrowsableKey,
.volumeIsLocalKey,
.isVolumeKey,
]
let manager = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys)
if let urls = manager {
print(urls)
}
This code is working fine for MacOS, however on the iOS side it always returns nil. Is there any known workaround?
Thanks!

Get Contact Image Data using ABPersonCopyImageData

I'm trying to get the contact details out of the address book on the Mac. I can get the first name and last name fields etc, but I'm struggling with the syntax for ABPersonCopyImageData.
Now according to the documentation ABPersonCopyImageData takes a single parameter of type ABPerson.
Here is my code:
import AddressBook
let thisPerson : ABPerson
let addressBook = ABAddressBook.sharedAddressBook()
rec = addressBook.recordForUniqueId("0005A360-327F-4E12-BBB9-24A842497E12:ABPerson")
let firstName = rec.valueForProperty(kABFirstNameProperty) as! String
let lastName = rec.valueForProperty(kABLastNameProperty) as! String
println("\(firstName) \(lastName)")
let contactImage = ABPersonCopyImageData(thisPerson)
The last line stops the compiler with an error: Cannot invoke 'ABPersonCopyImageData' with an argument list of type (ABPerson). As far as I can tell thisPerson is of type ABPerson. What is going wrong?
I found out how to do this in ElCapitan:
import Contacts
func getContactImage(name:String) -> NSImage?
{
let store = CNContactStore()
do
{
let contacts = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName(name), keysToFetch:[CNContactImageDataKey])
if contacts.count > 0
{
if let image = contacts[0].imageData
{
return NSImage.init(data: image)
}
}
}
catch
{
}
return nil
}

Cocoa/Swift: Loop through names of folder in path

I'm currently programming an os x application with swift, but I can't figure how to loop through or even get the names of all folders at a certain path. Maybe something with fm.enumeratorAtPath?
I use enumeratorAtURL. Here's some code that shows an example of how to print the directories in the user's home directory.
if let dirURL = NSURL(fileURLWithPath: NSHomeDirectory()) {
let keys = [NSURLIsDirectoryKey, NSURLLocalizedNameKey]
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtURL(
dirURL,
includingPropertiesForKeys: keys,
options: (NSDirectoryEnumerationOptions.SkipsPackageDescendants |
NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants |
NSDirectoryEnumerationOptions.SkipsHiddenFiles),
errorHandler: {(url, error) -> Bool in
return true
}
)
while let element = enumerator?.nextObject() as? NSURL {
var getter: AnyObject?
element.getResourceValue(&getter, forKey: NSURLIsDirectoryKey, error: nil)
let isDirectory = getter! as Bool
element.getResourceValue(&getter, forKey: NSURLLocalizedNameKey, error: nil)
let itemName = getter! as String
if isDirectory {
println("\(itemName) is a directory in \(dirURL.absoluteString)")
//do something with element here.
}
}
}

Type 'CFStringRef' does not conform to protocol 'Hashable' in Xcode 6.1

In my app i have a Keychain access class that was working in Xcode 6 but now in Xcode 6.1 i get some errors this is the first one: the Type 'CFStringRef' does not conform to protocol 'Hashable':
private class func updateData(value: NSData, forKey keyName: String) -> Bool {
let keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
let updateDictionary = [kSecValueData:value] //HERE IS THE ERROR
// Update
let status: OSStatus = SecItemUpdate(keychainQueryDictionary, updateDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
I also get a error similar to the the first one but it is: Type 'CFStringRef' does not conform to protocol 'NSCopying' here is the part where i get this error:
private class func setupKeychainQueryDictionaryForKey(keyName: String) -> NSMutableDictionary {
// Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: NSMutableDictionary = [kSecClass:kSecClassGenericPassword]
// HERE IS THE ERROR ↑↑↑
// Uniquely identify this keychain accessor
keychainQueryDictionary[kSecAttrService as String] = KeychainWrapper.serviceName
// Uniquely identify the account who will be accessing the keychain
var encodedIdentifier: NSData? = keyName.dataUsingEncoding(NSUTF8StringEncoding)
keychainQueryDictionary[kSecAttrGeneric as String] = encodedIdentifier
keychainQueryDictionary[kSecAttrAccount as String] = encodedIdentifier
return keychainQueryDictionary
}
Can somebody tells me how to solve these error please.
CFStringRef is bridged with NSString which is bridged with String. The simplest solution is to just cast kSecValueData and kSecClass to Strings or NSStrings:
Here:
let updateDictionary = [kSecValueData as String: value]
And here:
var keychainQueryDictionary: NSMutableDictionary = [kSecClass as NSString: kSecClassGenericPassword]
I think it will be more readable
let keychainQueryDictionary : [String: AnyObject] = [
kSecClass : kSecClassGenericPassword,
kSecAttrService : serviceIdentifier,
kSecAttrAccount : accountName
]

List files in iTunes shared folder using Swift

I would like to list all files in my iTunes shared folder in a 'Table View' using Swift.
I check on Google and nobody talk about it, it look like it's a uncommon need, so if anyone can help it would be really helpful.
EDIT: I found three links talking about it but in Objective-C, I have no experience in this language. If someone understand this, here are the links.
http://www.exampledb.com/objective-c-get-itunes-file-sharing-folder-files-with-full-path.htm
http://www.infragistics.com/community/blogs/stevez/archive/2013/10/14/ios-objective-c-working-with-files.aspx
http://www.raywenderlich.com/1948/itunes-tutorial-for-ios-how-to-integrate-itunes-file-sharing-with-your-ios-app
Based on this objective-C tutorial http://mobiforge.com/design-development/importing-exporting-documents-ios, I created three methods: listFilesFromDocumentsFolder which returns a list of the names of all documents I have in the apps iTunes shared folder and loadFileFromDocumentsFolder which loads the url for a given filename and passes the url to handleDocumentOpenUrl to load the file on a UIWebView. Find below the three methods.
You can also download the project from github: https://github.com/Euniceadu/Load-Shared-Documents
listFilesFromDocumentsFolder
func listFilesFromDocumentsFolder() {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var fileManager: NSFileManager = NSFileManager()
var fileList: NSArray = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: nil)!
var filesStr: NSMutableString = NSMutableString(string: "Files in Documents folder \n")
for s in fileList {
filesStr.appendFormat("%#", s as String)
}
self.displayAlert(filesStr)
}
loadFileFromDocumentsFolder
func loadFileFromDocumentsFolder(fileName: String) {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var filePath: String = documentsDirectory.stringByAppendingPathComponent(fileName);
var fileUrl: NSURL = NSURL(fileURLWithPath: filePath);
self.handleDocumentOpenURL(fileUrl)
}
handleDocumentOpenUrl
func handleDocumentOpenURL(url: NSURL) {
var requestObj = NSURLRequest(URL: url)
webView.userInteractionEnabled = true
webView.loadRequest(requestObj)
}
Hope this helps.

Resources