Update
I have since created a screencast on how to add an image to a UITableView.
You can a view a more complete example and screen cast of how do this here.
You’ve got all those lovely images you’ve taken on your iPhone, and you want to display them in a table as thumbnails in your iphone app. How do you do it?
Drag out a new Table View Controller
Create and associate a new UIViewController subview class (i.e. TableViewController) and associate it with the controller.
Define a model to hold the photos:
TableViewController.h
#import <UIKit/UIKit.h> @interface TableViewController : UITableViewController @property (nonatomic, strong) NSArray *photos; @end
Sythethize the photos property, add a setter to refresh the model in case it changes, and get rid of all the template code save the stuff shown below.
TableViewController.m
#import "TableViewController.h" @implementation TableViewController @synthesize photos = _photos; -(void)setPhotos:(NSArray *)photos { if (_photos != photos) { _photos = photos; [self.tableView reloadData]; } } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 0; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.photos 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]; } // Configure the cell... return cell; } @end
Give your table cell an identifier
And then update the reference in code
static NSString *CellIdentifier = @"MyPhotos";
Getting the pictures
First import and add a reference to the library.
#import <AssetsLibrary/AssetsLibrary.h>.
Then use the Asset library to iterate through all your photos, and collect them in the photo model we setup.
TableViewController.m
- (void) viewWillAppear:(BOOL)animated { // collect the photos NSMutableArray *collector = [[NSMutableArray alloc] initWithCapacity:0]; ALAssetsLibrary *al = [TableViewController defaultAssetsLibrary]; [al enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) { if (asset) { [collector addObject:asset]; } }]; self.photos = collector; } failureBlock:^(NSError *error) { NSLog(@"Boom!!!");} ]; }
Set the display table
This is pretty easy. Basically we are going to pull the asset(s) we stored in our photo model, and display the thumbnail in the table cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"MyPhotos"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // Configure the cell... ALAsset *asset = [self.photos objectAtIndex:indexPath.row]; [cell.imageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]]; [cell.textLabel setText:[NSString stringWithFormat:@"Thing %d", indexPath.row+1]]; return cell; }
Gotcha
Assets don’t like to hang around longer than their parents. So if we are going to access our assets latter we need to keep a reference to the library that created them around.
That’s what this singleton method is for:
TableViewController.h
+ (ALAssetsLibrary *)defaultAssetsLibrary;
TableViewController.m
+ (ALAssetsLibrary *)defaultAssetsLibrary { static dispatch_once_t pred = 0; static ALAssetsLibrary *library = nil; dispatch_once(&pred, ^{ library = [[ALAssetsLibrary alloc] init]; }); return library; }
You’ll know you’re hitting this problem if you get an error message that says something like: Invalid attempt to access ALAssetPrivate.
Test and Debug
To test this you are going to need to hook your iPhone up to your dev environment (the simulator can’t do camera).
Also things like this rarely work for me first time through. To debug try dropping logs files and check things like photo count when created:
NSLog(@"count: %d", [self.photos count]);
When creating this blog post I forgot to delete the table section template:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 0; }
Which caused it to display an empty screen.
You can also check that your assets are coming through with code like this:
// Configure the cell... ALAsset *asset = [self.photos objectAtIndex:indexPath.row]; ALAssetRepresentation *representation = [asset defaultRepresentation]; NSURL *url = [representation url]; NSLog(@"url: %@", [url absoluteString]);
Which will tell you if you are at least getting the images when you need to display them.
Hit the play button, and hopefully you should see something that looks like this:
Other things to check:
– make sure your viewController is hooked up to your class (this is from another example but you get the idea)
Good luck!
Helper links:
http://itunes.apple.com/itunes-u/ipad-iphone-application-development/id473757255 (Lecture 10 has a nice walkthrough)
http://stackoverflow.com/questions/3837115/display-image-from-url-retrieved-from-alasset-in-iphone
Roman Balmus
Mar 15, 2012 @ 14:12:59
hi, how can i get photos from camera and display them in a tableview? tnx.
Van
Aug 22, 2012 @ 20:19:41
Hello. How do I solve a problem where assets (videos) that were deleted from the IOS Simulator album still show up in my table? I reloaded my tables, but that doesn’t solve the problem. In fact, I stopped the application and rebuilt it but it still keeps finding assets that I have deleted. Can you tell me why and what I need to do? Thanks.
JR
Aug 26, 2012 @ 12:34:29
Hi Van,
Without seeing the code it’s hard to say. You are on the right track in verifying that you are clearing your table.
The other thing you can do is to completely remove the app from your simulator, and then rerun the program. If the bug persists, you’ll at least know it’s your code – and not the simulator.
Good luck!
Zhenyi Zhang
Oct 20, 2012 @ 20:53:31
Great post! I’ve struggled for an afternoon trying to get all the photos from iphone. And it works with your code !!!
Thanks for sharing it ~~
JR
Oct 21, 2012 @ 23:35:13
You are very welcome. Glad you enjoyed it.
Ry
Mar 04, 2014 @ 23:04:04
hey I built the app but cant get it to use my camera.
my phone (iphone 5s) is hooked up (running most current OS on it) and running xcode 5.2.
Is there something i am missing?
I have a developer account but let my payed licence lapse.
the ap loads in the simulator (no errors) but does nothing when I hit the camera button. it doesnt even crash like i thought it should (normally)
What would be really helpful is a bit of code to load / open the photo library and choose pics from there if the camera is not available.
any and all help is good and appreciated.
thx
Shanmugasundharam Selvadurai
Jan 27, 2015 @ 13:19:35
Hi, thank for the good tutorial , and i have one question how to add manually image in Tableview by choosing the image in library.
sohil
Jul 29, 2015 @ 11:09:14
Nice Tutorial…Thanx…
uzair
Sep 07, 2015 @ 06:19:40
if i want to access the videos and showing them in the same way..what i have to do then ?