dhaval shah
dhaval shah

Reputation: 4549

Check file exists in directory with prefix of file name in Swift

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
}

Upvotes: 0

Views: 777

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

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");
        }
    }
}

Upvotes: 1

Related Questions