iOS Development

ios – How does the swiftUI programming language in xcode get knowledge from sqlite information?

Spread the love


struct ContentView: View {
    @State personal var searchTerm: String = ""
    @State personal var meanings: [String] = []

    @ObservedObject personal var dbManager = DatabaseManager()
    @ObservedObject personal var wordsManager = WordsManager(databaseManager: DatabaseManager())
    
    init() {
        let databaseManager = DatabaseManager()
        self.wordsManager = WordsManager(databaseManager: databaseManager)
        dbManager.copyDatabaseIfNeeded()
        wordsManager.fetchWords()
        print("Loaded phrases: (wordsManager.phrases)")
    }
......
    var physique: some View {
        NavigationView {
            VStack {
                HStack {
                    TextField("输入单词", textual content: $searchTerm, onEditingChanged: { _ in
                        updateList()
                    })
                    .autocapitalization(.none)
                    .padding()
                    .body(peak: 40)
                    .textFieldStyle(RoundedBorderTextFieldStyle())

                    Button("查找") {
                        findMeanings(for: searchTerm)
                    }
                    .padding()
                    .body(peak: 40)
                    .foregroundColor(.white)
                    .background(Colour.blue)
                    .cornerRadius(10)
                }
                .padding()
                .navigationTitle("词典")

                Divider()

                Listing(wordsManager.phrases.filter  searchTerm.isEmpty , id: .self) { phrase in
                    NavigationLink(vacation spot: DetailView(phrase: phrase, that means: meanings.first ?? "未找到含义")) {
                        Textual content(phrase)
                            .body(maxWidth: .infinity, alignment: .main)
                            .contentShape(Rectangle())
                    }
                }
                .listStyle(PlainListStyle())
                .background(Colour.grey.opacity(0.1))

                Spacer()
            }
            .padding()
            .navigationTitle("词典")
        }
    }
......

Copy the present relative path of the db file (construction and knowledge) to the native, after which get the info in sqlite displayed within the checklist

I am afraid the code is not detailed sufficient to confuse you. I am new to XCode

class DatabaseManager: ObservableObject {
    var db: OpaquePointer?

    init() {
         if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
             let sandboxDBPath = documentsPath.appendingPathComponent("english_grammar_today.db").path
             print("沙盒中的数据库路径:(sandboxDBPath)")

             // 打开数据库
             if sqlite3_open(sandboxDBPath, &db) == SQLITE_OK {
                 // 在这里执行你的操作
                 print("成功打开数据库")
             } else {
                 let errorMessage = String(cString: sqlite3_errmsg(db))
                 print("无法打开数据库,错误消息:(errorMessage)")
             }
             
             // 创建表
             if sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS dictionary (id INTEGER PRIMARY KEY AUTOINCREMENT, entry TEXT, paraphrase TEXT);", nil, nil, nil) != SQLITE_OK {
                 fatalError("无法创建数据库表")
             }
         } else {
             print("找不到应用沙盒的文档目录")
         }
     }

    
    func copyDatabaseIfNeeded() {
        if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let bundleDBPath = Bundle.fundamental.path(forResource: "english_grammar_today", ofType: "db")
            let sandboxDBPath = documentsPath.appendingPathComponent("english_grammar_today.db").path
            if !FileManager.default.fileExists(atPath: sandboxDBPath) {
                do {
                    attempt FileManager.default.copyItem(atPath: bundleDBPath!, toPath: sandboxDBPath)
                    print("成功拷贝数据库文件到应用沙盒 copy successed")
                    
                    // shut
                    if sqlite3_close(db) != SQLITE_OK {
                        print("无法关闭SQLite数据库连接 cannot shut")
                    }
                    
                    // retry
                    if sqlite3_open(sandboxDBPath, &db) == SQLITE_OK {
                        print("成功重新打开数据库")
                    } else {
                        let errorMessage = String(cString: sqlite3_errmsg(db))
                        print("无法重新打开数据库,错误消息:(errorMessage)")
                    }
                } catch {
                    print("copy failed:(error)")
                }
            } else {
                print("database file already exists")
            }
        } else {
            print("not discovered")
        }
    }


    deinit {
        // 关闭数据库连接
        if sqlite3_close(db) != SQLITE_OK {
            print("无法关闭SQLite数据库连接  failed")
        }
    }
}

Receive the doc listing of the applying sandbox, construct the trail of the database file within the sandbox, output the database path within the sandbox, and open the database.

Truly, I do not perceive. What’s a sandbox

However I do not know if the WordsManager downside is an issue or the DatabaseManager downside

class WordsManager: ObservableObject {
    @Revealed var phrases: [String] = []

    var databaseManager: DatabaseManager

    init(databaseManager: DatabaseManager) {
        self.databaseManager = databaseManager
        // 调用 fetchWords 方法以获取单词列表
        fetchWords()
    }

    func fetchWords() {
        var assertion: OpaquePointer?

        let question = "SELECT entry FROM dictionary"

        if sqlite3_prepare_v2(databaseManager.db, question, -1, &assertion, nil) == SQLITE_OK {
            var fetchedWords: [String] = []

            whereas sqlite3_step(assertion) == SQLITE_ROW {
                if let consequence = sqlite3_column_text(assertion, 0) {
                    let phrase = String(cString: consequence)
                    fetchedWords.append(phrase)
                }
            }

            sqlite3_finalize(assertion)

            if fetchedWords.isEmpty {
                print("未找到单词")
            } else {
                print("找到的单词:(fetchedWords)")
            }

            DispatchQueue.fundamental.async {
                self.phrases = fetchedWords
            }

        } else {
            let errorMessage = String(cString: sqlite3_errmsg(databaseManager.db))
            print("SQLite查询错误: (errorMessage)")
        }
    }
}

12 thoughts on “ios – How does the swiftUI programming language in xcode get knowledge from sqlite information?

  1. I do agree with all the ideas you have introduced on your post They are very convincing and will definitely work Still the posts are very short for newbies May just you please prolong them a little from subsequent time Thank you for the post

  2. of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again

  3. I enjoyed it just as much as you will be able to accomplish here. You should be apprehensive about providing the following, but the sketch is lovely and the writing is stylish; yet, you should definitely return back as you will be doing this walk so frequently.

Leave a Reply

Your email address will not be published. Required fields are marked *