0

I want to add my own Database named Photos.sqlite to my iOS application. I have the following code to open the database, but is this creating a database named Photos.sqlite, and not using my own?

func createDB() -> OpaquePointer?{
        let filePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathExtension(path)
        

        
        var db : OpaquePointer?
        
        guard sqlite3_open(filePath.path, &db) == SQLITE_OK else {
            print("error opening database")
            sqlite3_close(db)
            db = nil
            return nil
        }
        

        
        return db
                
            
    }

I am asking how would I use my own database within the application? Where would I put the file? I did a bit of research and it states the Photos.sqlite must be in documents but I do not think I need this since I will only be reading data from the database, I will not be inserting or updating the database in any way.

  • You can't read from a database if you haven't written into it first. Only user generated data should be in the documents folder. Where is "your" database? How does your database get its content? – lorem ipsum Oct 24 '21 at 22:02
  • @loremipsum I have already downloaded the data from unspash website. I did my own create tables and loading the data from a tab separated file. – Justin Philip Fulkerson Oct 24 '21 at 22:17
  • if it's going to be a static part of your app you could just add it to your Bundle and read it from there. – flanker Oct 24 '21 at 22:56
  • SQLite is an SQL database, which means that you need to make a query to get data. So do more research and find out how to make an SQL query. – El Tomato Oct 24 '21 at 23:03
  • @flanker Ok I added it to my project and selected a target membership. Would I have to specify the full path or would I leave it as "Photos.sqlite" ? It is still not recognizing any select statements :( – Justin Philip Fulkerson Oct 24 '21 at 23:17
  • It is not an exact duplicate because of the different language, but this question https://stackoverflow.com/questions/23236554/sqlite3-from-bundle-resources-in-ios is effectively the same as yours but using Objective-C. The approach is to put your database in the app bundle and copy it to your documents directory on first launch. – JeremyP Oct 25 '21 at 08:56
  • And here's some code in Swift to copy a db from the bundle to documents https://gist.github.com/rd13/320b3fed4d5f10ab8ea833b3f9818980 – JeremyP Oct 25 '21 at 09:01

0 Answers0