cyclingIsBetter
cyclingIsBetter

Reputation: 17591

IOS: open sqlite from an URL

I want open a sqlite db but it is not in my mainBundle but in a server then I don't have this

NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"info.sqlite"];

but I have

NSString *filePath = @"http://serverAddress/info.sqlite";
NSURL *url = [NSURL URLWithString:filePath];
NSData *myData = [NSData dataWithContentsOfURL:url];

and when I read this db what I can do? If my db is inside mainBundle I do this:

if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {

        const char *sql = "select id, one, two from TABLE";
        sqlite3_stmt *selectstmt;

        if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {

            while(sqlite3_step(selectstmt) == SQLITE_ROW) {

                idNum = [NSNumber numberWithInt:(int)sqlite3_column_int(selectstmt, 0)];
                ...
                ...

but if I have a NSData? Can you help me?

Upvotes: 2

Views: 1724

Answers (2)

redent84
redent84

Reputation: 19249

SQLite is "server-less", you cannot access from your device to a SQLite file hosted in a server. If it's read-only database, you can download it first or you can use a different database server (and client)

To save the file to documents directory and later read it, add the following code:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:@"database.sqlite"];

[data writeToFile:filePath atomically:NO];

Probably your best bet is to publish a thin web-service wrapper around the database. There are more pros that cons using a web-service instead of direct remote database access, take a look to this blog post for further explanations.

Upvotes: 3

Prasad De Zoysa
Prasad De Zoysa

Reputation: 2567

I guess you want to download the latest database bundle instead of bundling it when you releasing the application, so now you have downloaded the database file and it is available in NSData format.

If so the slution is simple, you can simply save the NSData to file in to your document directory (Refer this how to save NSData to file), and contnue loading your bundle as normal way. like this,

NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"info.sqlite"];

remember before you load file "info.sqlite", you need to save to the file from NSData. I haven't try this, but it should work :)

Happy coding!!!

Upvotes: -1

Related Questions