Edward Hasted
Edward Hasted

Reputation: 3433

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?

Upvotes: 0

Views: 555

Answers (2)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

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)!

Upvotes: 1

ipraba
ipraba

Reputation: 16553

I hope this will work

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")
    if let path = NSBundle.mainBundle().resourcePath
    {
      let fromPath = "\(path)/\(fileName)"
      fileManager.copyItemAtPath(fromPath, toPath: dbPath)
    }
  }
}

Upvotes: 0

Related Questions