Search code examples
swiftnsfilemanager

Swift 2.0 copyFile EXC_BAD_INSTRUCTION


Been updating some code to 2.0 and my replaced copyFile routine is returning "fatal error: unexpectedly found nil while unwrapping an Optional value" The // line was how I was doing this previously.

 class func copyFile(fileName: String) {
    let dbPath: String = getPath(fileName as String)
    let fileManager = NSFileManager.defaultManager()
    if !fileManager.fileExistsAtPath(dbPath) {
        let fromPath = NSBundle.mainBundle().pathForResource(fileName , ofType: "db")
        // let fromPath: String = NSBundle.mainBundle().resourcePath.URLByAppendingPathComponent(fileName)
        do {
            try fileManager.copyItemAtPath(fromPath!, toPath: dbPath)
        } catch _ {
        }
    }
}

How do I go about resolving this?


Solution

  • resourcePath returns optional value just use ? before using any method

    let fromPath: String = NSBundle.mainBundle().resourcePath?.URLByAppendingPathComponent(fileName)
    

    Also URLByAppendingPathComponent is not a member of NSString. Did you mean resourceURL?

    In that case use this

    let fromUrl = NSBundle.mainBundle().resourceURL?.URLByAppendingPathComponent(fileName)
    let fromPath: String = (fromUrl?.path)!