0

I want to check whether my File is exist with just prefix of file name in SWIFT.

E.g

My file name is like Companies_12344

So after _ values are dynamic but "Companies_" is static.

How can i do that?

I have already done split filename code below

How can i check through NSFileManager for is exist file name with "Companies_"

My code below For split

 func splitFilename(str: String) -> (name: String, ext: String)? {
    if let rDotIdx = find(reverse(str), "_")
    {
        let dotIdx = advance(str.endIndex, -rDotIdx)
        let fname = str[str.startIndex..<advance(dotIdx, -1)]
        println("splitFilename >> Split File Name >>\(fname)")
    }


    return nil
}
dhaval shah
  • 4,499
  • 10
  • 29
  • 42
  • For the split you can just do str.componentsSeparatedByString("_") – Arbitur Jul 09 '15 at 09:43
  • yes that's fine...But with that prefix name how can i check if the file is exist or not from NSFileManager? – dhaval shah Jul 09 '15 at 09:44
  • 1
    Where is the difference to your previous question http://stackoverflow.com/questions/31295161/check-filename-is-exist-by-prefix-in-swift ? – Martin R Jul 09 '15 at 09:45
  • Martin, previous one was about the file name to be split and it was a bit confusing.. So I have added it more precisely this time NSFIlemanager... – dhaval shah Jul 09 '15 at 09:50

1 Answers1

1

I think this code you need:

let str = "Companies_12344"

if str.hasPrefix("Companies") {
    println("Yes, this one has 'Companies' as a prefix")
    let compos = str.componentsSeparatedByString("_")
    if let file = compos.first {

        println("There was a code after the prefix: \(file)")
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String

        var yourPath = paths.stringByAppendingPathComponent("\(file)_")

        var checkValidation = NSFileManager.defaultManager()

        if (checkValidation.fileExistsAtPath(yourPath))
        {
            println("FILE AVAILABLE");
        }
        else
        {
            println("FILE NOT AVAILABLE");
        }
    }
}
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165