How Can I Save & Retrieve an image (bytes) to SQLi

2019-02-05 09:40发布

问题:

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.

回答1:

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.



回答2:

Check out main.m in the FMDB distribution- it shows how to save and pull out a binary blob (using the safari icon as an example)".