Ios 如何在项目中查找文件
我非常想在我的项目中找到一个文件 我在Interface.plist等支持文件中有一个文件:Database.sqlite3 此代码找到plist但没有数据库:Ios 如何在项目中查找文件,ios,swift,Ios,Swift,我非常想在我的项目中找到一个文件 我在Interface.plist等支持文件中有一个文件:Database.sqlite3 此代码找到plist但没有数据库: let bundle = NSBundle.mainBundle() let envsPListPath = bundle.pathForResource("Interface", ofType:"plist") let environments = NSDictionary(contentsOfFile: en
let bundle = NSBundle.mainBundle()
let envsPListPath = bundle.pathForResource("Interface", ofType:"plist")
let environments = NSDictionary(contentsOfFile: envsPListPath!)
请问我如何获取数据库文件的路径?我确实尝试了很多解决方案,但对于移动设备中的文档,不在项目目录中。尝试以下方法:
let strDbPath = NSBundle.mainBundle().pathForResource("Database", ofType:"sqlite")
通过这种方式,您可以在获得可根据需要访问的路径后,在捆绑包中创建sqlite的完整路径通常复制到文档目录中以进行进一步操作 它也可以通过这种方式访问
class func copyFile(fileName: NSString) {
let dbPath: String = getPath(fileName as String)
let fileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(dbPath) {
let documentsURL = NSBundle.mainBundle().resourceURL
let fromPath = documentsURL!.URLByAppendingPathComponent(fileName as String)
var error : NSError?
do {
try fileManager.copyItemAtPath(fromPath.path!, toPath: dbPath)
} catch let error1 as NSError {
error = error1
}
let alert: UIAlertView = UIAlertView()
if (error != nil) {
alert.title = "Error Occured"
alert.message = error?.localizedDescription
} else {
alert.title = "Successfully Copy"
alert.message = "Your database copy successfully"
}
alert.delegate = nil
alert.addButtonWithTitle("Ok")
alert.show()
}
}
您可以在函数中传递文件名(Database.sqlite3)
有关如何在swift中使用sqlite的完整演示,请参阅本网站: 在您的代码中,如果您试图使用示例代码获取db文件,那么当您试图从sqlite3文件检索NSDictionary时,将出现错误,这是不可能的
plist文件存储在NSDictionary结构中,以便代码能够正确执行您是否尝试过以下明显的方法:
bundle.pathForResource(“数据库”,类型:“sqlite3”)
?发布您用于尝试查找数据库的代码。sqlite3
文件是的,我尝试过,并且始终是“nil”如果它是nil
,那么您的应用程序包中实际上没有名为Database.sqlite3
的文件。确保文件名的大小写匹配。谢谢,但是当我使用:let strDbPath=NSBundle.mainBundle().pathForResource(“Database”,of type:“sqlite3”)-strDbPath为nil时。你知道为什么吗?@ankmara请尝试以下方法:让strDbPath=NSBundle.mainBundle().pathForResource(“数据库”,类型:“sqlite”)如果不起作用,请清理并重新构建项目,并检查是否有“Database.sqlite3”(检查文件的拼写)在项目的复制捆绑资源
的构建阶段