简体   繁体   中英

How do i retrieve image from SQLite and display in UIImageView

I save all my images in a folder in Xcode and name all the link in SQLite according to the name in the folder. I am using BLOB in SQLite to store the image. How do i get my UIImage to display the image that i want from SQLite? It is suppose to be displayed after pressing a character name from the TableView and it will move to the ViewController to display the image.

This is the AppDelegate.m file:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Setup some globals
databaseName = @"Database.sql";

// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];

// Query the database for all records and construct the array
[self readCharactersFromDatabase];
[self readChaptersFromDatabase];
[self readThemesFromDatabase];
//[self readPlotsFromDatabase];

// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}

-(void) readCharactersFromDatabase {
// Setup the database object
sqlite3 *database;

// Init the Array
chars = [[NSMutableArray alloc] init];

// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    // Setup the SQL Statement and compile it for faster access
    const char *sqlStatement = "select * from Character";
    sqlite3_stmt *compiledStatement;
    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
        // Loop through the results and add them to the feeds array
        while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
            // Read the data from the result row
            NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
            NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
            UIImage *aImage = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

            // Create a new object with the data from the database
            Character *characters = [[Character alloc] initWithName:aName description:aDescription image:aImage];

            // Add the object to the Array
            [chars addObject:characters];

            //[characters release];
        }
    }
    // Release the compiled statement from memory
    sqlite3_finalize(compiledStatement);

}
sqlite3_close(database);

}

@end

This is the TableViewController.m file:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [appDelegate.chaps count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

// Set up the cell

Chapter *chapters = (Chapter *)[appDelegate.chaps objectAtIndex:indexPath.row];

cell.textLabel.text = chapters.name;
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic -- create and push a new view controller

Chapter *chapters = [appDelegate.chaps objectAtIndex:indexPath.row];

if(chapView == nil) 
    chapView = [self.storyboard instantiateViewControllerWithIdentifier:@"chapter"];
// self.charView = viewController;


chapView.chapters = chapters;

chapView.chapDes = chapters.description;

[self.navigationController presentModalViewController:chapView animated:YES];

// [charView release];

}

- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to add the Edit button to the navigation bar.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];  
self.title = @"Chapter Analysis";
}

-(IBAction)backbutton {
ViewController *mainPage = [self.storyboard instantiateViewControllerWithIdentifier:@"mainPage"];


[self.navigationController presentModalViewController:mainPage animated:YES];
}

@end

And this is the ViewController.m file:

// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
// self.title = characters.name;
charImage.image =  charI;
charDescription.text = charDes;
[super viewDidLoad];
}

-(IBAction)backbutton {
CharacterTableViewController *characterTable = [self.storyboard instantiateViewControllerWithIdentifier:@"characterTable"];


[self.navigationController presentModalViewController:characterTable animated:YES];
}

@end

I have no idea where is the error at and why I am not able to display anything out at all.

EDIT

I change my variable for storing the image in SQLite to text and i just input the image name. In Xcode, I have a image folder with all the images that i need and the name of the images is the same as the one i stored in the database. I used this line of code to retrieve the image name from the database and displayed it out in the UIImage.

charView.image = [UIImage imageNamed:characters.image]; 

Saving the image data in the database is such a bad idea, because there is a big chance to get your database file to become corrupted. If you want to cache images, better use the approach of downloading and saving those images into your documents folder.

Just you set like this way I assume you use NSData UIImagePNGRepresentation and then use sqlite3_column_blob instead of sqlite3_column_text .

Instead of UIImage *aImage = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

set like this,I hope it will help you.

NSData *imageDataFromDb = [[NSData alloc]initWithBytes:sqlite3_column_blob(compiledStatement, 3) length:sqlite3_column_bytes(compiledStatement, 3)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM