Get mounted volumes list with Swift?

| | August 5, 2015

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: ""))
        }

One Response to “Get mounted volumes list with Swift?”

  1. 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)
                }
            }
        }
    }
    

Leave a Reply