Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFileManager fileExistsAtPath:isDirectory and swift

Tags:

swift

I'm trying to understand how to use the function fileExistsAtPath:isDirectory: with Swift but I get completely lost.

This is my code example:

var b:CMutablePointer<ObjCBool>?  if (fileManager.fileExistsAtPath(fullPath, isDirectory:b! )){     // how can I use the "b" variable?!     fileManager.createDirectoryAtURL(dirURL, withIntermediateDirectories: false, attributes: nil, error: nil) } 

I can't understand how can I access the value for the b MutablePointer. What If I want to know if it set to YES or NO?

like image 227
MatterGoal Avatar asked Jul 11 '14 10:07

MatterGoal


2 Answers

The second parameter has the type UnsafeMutablePointer<ObjCBool>, which means that you have to pass the address of an ObjCBool variable. Example:

var isDir : ObjCBool = false if fileManager.fileExistsAtPath(fullPath, isDirectory:&isDir) {     if isDir {         // file exists and is a directory     } else {         // file exists and is not a directory     } } else {     // file does not exist } 

Update for Swift 3 and Swift 4:

let fileManager = FileManager.default var isDir : ObjCBool = false if fileManager.fileExists(atPath: fullPath, isDirectory:&isDir) {     if isDir.boolValue {         // file exists and is a directory     } else {         // file exists and is not a directory     } } else {     // file does not exist } 
like image 146
Martin R Avatar answered Oct 13 '22 04:10

Martin R


Tried to improve the other answer to make it easier to use.

enum Filestatus {         case isFile         case isDir         case isNot } extension URL {               var filestatus: Filestatus {         get {             let filestatus: Filestatus             var isDir: ObjCBool = false             if FileManager.default.fileExists(atPath: self.path, isDirectory: &isDir) {                 if isDir.boolValue {                     // file exists and is a directory                     filestatus = .isDir                 }                 else {                     // file exists and is not a directory                     filestatus = .isFile                 }             }             else {                 // file does not exist                 filestatus = .isNot             }             return filestatus         }     } } 
like image 42
Jonny Avatar answered Oct 13 '22 05:10

Jonny