user1858725
user1858725

Reputation: 1333

how to check if file exist use swift, rewrite from objective c

how to rewrite this objective-c language to swift?

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

regards.

Upvotes: 5

Views: 8388

Answers (3)

vadian
vadian

Reputation: 285039

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
}

Upvotes: 4

Brandon A
Brandon A

Reputation: 8279

let path = "/Applications/MySample.app"
let hasFile = FileManager().fileExists(atPath: path)
if hasFile {
    // use file
}
else {
    // possibly inform user the file does not exist
}

Upvotes: 0

Adeel Ur Rehman
Adeel Ur Rehman

Reputation: 566

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
}

Upvotes: 11

Related Questions