将一些代码更新为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 _ {
}
}
}
我该如何解决这个问题?
答案 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)
}
}
}