5

how to rewrite this objective-c language to swift?

NSString *filePath = @"/Applications/MySample.app";
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        // avoid open add friend
    }

regards.

user1858725
  • 1,293
  • 1
  • 11
  • 13
  • Check this answer - http://stackoverflow.com/questions/26931355/how-to-create-direcotry-using-swift-code/26931481#26931481 – Kampai Dec 22 '14 at 06:43

3 Answers3

11

Equivalent Swift 3 Code:

let filePath = "/Applications/MySample.app"
if (FileManager.default.fileExists(atPath: filePath)) {
    // avoid open add friend
}

Swift 2

let filePath = "/Applications/MySample.app"
if (NSFileManager.defaultManager().fileExistsAtPath(filePath))
{
    // avoid open add friend
}
bkribbs
  • 734
  • 1
  • 6
  • 24
Adeel Ur Rehman
  • 616
  • 5
  • 14
4

Some years after the question has been asked I recommend to take rewrite literally and use the URL related API

let fileURL = URL(fileURLWithPath:"/Applications/MySample.app")
if let _ = try? fileURL.checkResourceIsReachable()  {
   // file exists
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0
let path = "/Applications/MySample.app"
let hasFile = FileManager().fileExists(atPath: path)
if hasFile {
    // use file
}
else {
    // possibly inform user the file does not exist
}
Brandon A
  • 8,153
  • 3
  • 42
  • 77
  • I created a file manually in downlods folder.I tried to access that file with the code ```let fileDirectory="/Downloads/Receipt Data.txt" if FileManager().fileExists(atPath: fileDirectory) { print("file exists") } else{ print("file does not exist") }``` But it always says "file does not exist ".I am confused How to give directory for downloads.Anyone please clarify my doubts. – Priya Sri Jan 30 '20 at 10:38