1

For example I'd like to check if: Users/username/Desktop/folder is empty, or better check if it has files with an .png extension?

I'm really new at all this but if anyone knows please help me :)

  • Just select Desktop folder instead of Documents, filter png files and check if !isEmpty – Leo Dabus Dec 25 '15 at 23:23
  • Keep in mind that Swift leverages Cocoa and CocoaTouch to provide access to a wealth of features on OS X and iOS. This includes the `NSFileManager` class used in the answers below. Those frameworks predate Swift by many years, so in many cases you, will find a lot more resources by searching for Cocoa instead of Swift. Good luck! – hashemi Dec 25 '15 at 23:36
  • @Doni if you would like to get that folder URL programatically instead of hard coding it you can do like this: guard let desktopFolderUrl = NSFileManager.defaultManager().URLsForDirectory(.DesktopDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent("folder") else { return } – Leo Dabus Dec 26 '15 at 00:24
  • @LeoDabus thanks now how to implement it to that previous code from @codedifferent? Sorry but again I'm really new. Thanks for the help guys and merry christmas :) – safasfmasklfalskf Dec 26 '15 at 00:34
  • if you are gonna put it inside a method or inside viedDidLoad – Leo Dabus Dec 26 '15 at 00:40
  • guard let dropIconsHereURL = NSFileManager().URLsForDirectory(.DesktopDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent("Drop Icons Here") else { return } – Leo Dabus Dec 26 '15 at 00:40
  • if you need to use its path you can access dropIconsHereURL.path! or – Leo Dabus Dec 26 '15 at 00:42
  • guard let dropIconsHerePath = NSFileManager().URLsForDirectory(.DesktopDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent("Drop Icons Here").path else { return } – Leo Dabus Dec 26 '15 at 00:43

2 Answers2

5

Use contentsOfDirectoryAtPath to get the list of all files in a directoly, then filter the array for .png files

let path = "/Users/username/Desktop/folder"
do {
    let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
    let images = contents.filter { $0.lowercaseString.hasSuffix(".png") }
} catch let error as NSError {
    // Directory not exist, no permission, etc.
    print(error.localizedDescription)
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
0
let fileManager = NSFileManager.defaultManager()
let folderPath = "/Users/username/Desktop/folder"

if let contentEnumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath) {
    var numFilesWithSuffix = 0
    let mySuffix = "png"
    while let fileOrFolder = contentEnumerator.nextObject() as? String {
        if fileOrFolder.hasSuffix(mySuffix) {
            numFilesWithSuffix += 1 // count occurences
        }
    }
}
dfrib
  • 70,367
  • 12
  • 127
  • 192