Swift 2.0 copyFile EXC_BAD_INSTRUCTION

时间:2015-09-23 09:02:21

标签: swift nsfilemanager

将一些代码更新为2.0并且我替换的copyFile例程正在返回 “致命错误:在展开Optional值时意外发现nil” //行就是我之前的做法。

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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

在使用任何方法

之前,

resourcePath返回可选值,只需使用?

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

URLByAppendingPathComponent也不是NSString的成员。您的意思是resourceURL吗?

在这种情况下使用此

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

答案 1 :(得分:0)

我希望这会起作用

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