Swift 2.0 复制文件 EXC_BAD_INSTRUCTION

Swift 2.0 copyFile EXC_BAD_INSTRUCTION

正在将一些代码更新到 2.0,我替换的 copyFile 例程正在返回 "fatal error: unexpectedly found nil while unwrapping an Optional value" // 行是我之前的做法。

 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 _ {
        }
    }
}

我该如何解决这个问题?

resourcePath returns 可选值只需在使用任何方法之前使用 ?

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

另外 URLByAppendingPathComponent 不是 NSString 的成员。您是说 resourceURL 吗?

在那种情况下使用这个

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

我希望这会奏效

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