vendredi 12 juin 2015

How to download sqlite DB from server and use it in uitableview?

I have a download DB button to download a sqlite 3 database from server. When I click on it, the output can show "File Saved !" But when I try to access the DB, it shows "no such table". Can anyone help me with it? There's no problem if I add the same DB into xcode manually.

-(IBAction) downloadButtonPressed:(id)sender;{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"Downloading Started");
    NSString *urlToDownload = @"http://ift.tt/1JKserp";
    NSURL  *url = [NSURL URLWithString:urlToDownload];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    if ( urlData )
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];

        filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"authorsDb.sqlite"];

        //saving is done on main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [urlData writeToFile:filePath atomically:YES];
            NSLog(@"%@",filePath);

            NSLog(@"File Saved !");
            });
        } 
    });
}


    @try {
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"authorsDb.sqlite"];
    BOOL success = [fileMgr fileExistsAtPath:dbPath];
    if(!success)
    {
        NSLog(@"Cannot locate database file '%@'.", dbPath);
    }
    if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
    {
        NSLog(@"An error has occurred: %s", sqlite3_errmsg(db));

    }
    if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
    {
        NSLog(@"Problem with prepare statement:  %s", sqlite3_errmsg(db));
    }else{
        while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
            Author * author = [[Author alloc] init];
            author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
            author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
            author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
            [theauthors addObject:author];
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire