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

女生的网名这么多〃 提交于 2019-11-29 10:24:55

问题


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)".



来源:https://stackoverflow.com/questions/10454568/how-can-i-save-retrieve-an-image-bytes-to-sqlite-blob-using-fmdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!