Reputation: 671
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.
Upvotes: 3
Views: 4797
Reputation: 671
- (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.
Upvotes: 2
Reputation: 2916
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)".
Upvotes: 0