编辑:
正如Maddy所问的,我正在包括“打开”文件的代码:
我删除了一个应用程序,并通过Xcode再次运行它。在文档目录中没有文件之前,我检查了,并且由于没有文件,所以我可以从主包中复制我的32字节sqlite文件,其中包含我的表。
问题是,在我删除它之后,它在目录文件夹中创建了一个零字节有效sqlite文件,如果文档目录中没有文件,则在运行时它中没有表。因此,在app委托中,当我检查文件时,它正确地说,虽然不是我想要的文件。如果我手动转到设备中的iTunes并删除该文件,它将复制正确的文件。
这在模拟器和设备中都会发生。任何想法我都能做错什么。以下是来自应用程序委托的代码: Xcode 10.1和syntax 4.2语法:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Fabric.with([Crashlytics.self])
let sourcePath = Bundle.main.path(forResource: "mydb", ofType: "db")!
let fileManager = FileManager.default
let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let destinationPath = doumentDirectoryPath.appendingPathComponent("mydb")
if !fileManager.fileExists(atPath: destinationPath) {
do {
try fileManager.copyItem(atPath: sourcePath, toPath: destinationPath)
}
catch
{
os_log("error copying database")
Crashlytics.sharedInstance().recordError(error)
print(error)
}
}
return true
}打开文件的代码
import Foundation
import SQLite
import os.log
var connected: Bool
//MARK: - private attributes
var db: Connection?
//MARK: - constructor
init() {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
do {
db = try Connection("\(path)/mydb.db")
connected = true
}
catch {
connected = false
}
}事先非常感谢。这真让我费解。
发布于 2018-12-04 22:16:32
我使用的是Sqlite.swift,下面是Connection方法的构造函数:
/// Initializes a new SQLite connection.
///
/// - Parameters:
///
/// - location: The location of the database. Creates a new database if it
/// doesn’t already exist (unless in read-only mode).
///
/// Default: `.inMemory`.
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Returns: A new database connection.
public init(_ location: SQLite.Connection.Location = default, readonly: Bool = default) throws因此,如果不存在,则创建数据库(空白,没有表)。因此,我将编辑后的问题中的代码更改为:
//MARK: - constructor
init() {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
do {
let sourcePath = Bundle.main.path(forResource: "mydb", ofType: "db")!
let fileManager = FileManager.default
let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let destinationPath = doumentDirectoryPath.appendingPathComponent("mydb.db")
if !fileManager.fileExists(atPath: destinationPath) {
try fileManager.copyItem(atPath: sourcePath, toPath: destinationPath)
}
db = try Connection("\(path)/mydb.db")
connected = true
}
catch {
connected = false
}
}而且起作用了。非常感谢你提供的线索。
https://stackoverflow.com/questions/53604215
复制相似问题