Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Save & Retrieve an image (bytes) to SQLite (blob) using FMDB?

I'm making an iOS App that need to show some images from a remote site (from an URL), and everytime the users enter to the screen that should show the image, the app get freeze until the download is completed. So I want to store the images already downloaded into a SQLite Table named COVERS.

Here is the code that how I'm downloading and Showing the image:

Suppose that movieCover is an UIImageView and the object movie has a NSURL property named cover that contains the URL of the image to be downloaded.

NSData *cover = [[NSData alloc] initWithContentsOfURL:movie.cover];
movieCover.image = [[UIImage alloc] initWithData:cover];

But, I want to change it to something like this:

NSData *cover = [appDelegate.dataBase getCoverForMovie:movie];
if( !cover ) {
    cover = [[NSData alloc] initWithContentsOfURL:movie.cover];
    [appDelegate.dataBase setCover:cover ToMovie:movie];
}

movieCover.image = [[UIImage alloc] initWithData:cover];

Suppose that appDelegate is a property of the current ViewController, and dataBase is a property of the AppDelegate wich uses FMDB to manipulate the data in the DataBase.

I need to get the cover previously saved in the database using the method:

- (NSData *)getCoverForMovie:(Movie *)movie;

But, if there is not a cover saved, then return nil.

So I need to save the cover using the method

- (BOOL)saveCover:(NSData *)cover ForMovie:(Movie *)movie;

But I don't know how to code this method. Need some help with it.

like image 819
Alberto Estrella Avatar asked Dec 06 '25 14:12

Alberto Estrella


1 Answers

Methods Implementations based on fmdb.m examples

- (NSData *)getCoverForMovie:(Movie *)movie
{
    NSData *cover = nil;

    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    [db open];
    FMResultSet *results = [db executeQueryWithFormat:@"SELECT * FROM COVERS WHERE movie = %i", movie.movieID];

    if([results next])
    {
        cover = [results dataForColumn:@"cover"];
    }

    return cover;
}


- (BOOL)saveCover:(NSData *)cover ForMovie:(Movie *)movie
{
    BOOL result;

    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    [db open];

    result = [db executeUpdate:@"INSERT OR REPLACE INTO COVERS (movie, cover) VALUES (?,?)", movie.movieID, cover];

    return result;
}

Thanks to @ccgus for his answer.

like image 159
Alberto Estrella Avatar answered Dec 08 '25 05:12

Alberto Estrella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!