How to add images to UITableView from phone gallery - ios

I created in storyboard UITableView with prototype cell, TableViewController and UITableViewCell. Now I would like to choose all the pictures from phone gallery and save one or more to the database. But at this moment I need to implement adding pictures to tableview. I'm beginner in iOS. Can anyone tell me how can do that? give me a link or code? Thank you for advance

You can use ALAssetsLibrary in AssetsLibrary framework to fetch all images from phone gallery. Save each images in to an Array.
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != nil) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
NSURL *url= (NSURL*) [[result defaultRepresentation] url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
UIImage *img = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
[imgArray addbject:img];
}
failureBlock:^(NSError *error){ NSLog(#"operation failed"); } ];
}
}
};
Then you can use this array for saving to DB or to show in tableview.
For Using in TableView, you need to add UIImageView in your prototype cell, then set the images from the array to the cell accordingly. Your table view delegate methods will be like below.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [imgArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CellId = #"ImageCell";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId];
}
UIImage *img = [imgArray objectAtIndex:indexPath.row];
cell.imgView.image = img;
return cell;
}

If you want to pick the image from gallery and show it to tableview, you can use Custom ImageView in tableView or CustomCell imageView
First you need to pick the image from gallery and save it to array
Before that allocate and initialize the array in viewDidLoad method
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrayImage;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
arrayImage = [[NSMutableArray alloc]init];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image=[info objectForKey:#"UIImagePickerControllerOriginalImage"];
imageView.image=image;
[arrayImage addObject:image];
picker.delegate =self;
[picker dismissViewControllerAnimated:YES completion:nil];
}
Then in tableView
If you CustomCell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell==nil)
{
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"CustomTableViewCell" owner:self options:nil];
cell = nib[0];
}
cell.galleryImageView.image = [arrayImage objectAtIndex:indexPath.row];
return cell;
}
If you use default table view cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
cell.imageView.image = [arrayImage objectAtIndex:indexPath.row];
return cell;
}

Related

UItableView deplicated cell when scrolling

Sorry for posting this question again but I've looked into many answers and neither of them was helpfull to solve my issue.
So this my code :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"radioCell";
RadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}
[self configureCommentCell:cell atIndexPath:indexPath];
return cell;
}
when I scroll down my cell get mixed up and some of data are repeated, so I've tried this :
static NSString *CellIdentifier = #"memberCell";
RadioCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
and this :
RadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
}
But it didn't fixed my issue and I get white empty cells ? please how to fix this issue ?
Update
- (void)configureCommentCell:(RadioTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSDictionary *object;
if ([_dataArray[indexPath.section] isKindOfClass:[NSArray class]])
object = [_dataArray[indexPath.section] objectAtIndex:indexPath.row];
else
object = [[_dataArray[indexPath.section] valueForKey:#"radioList"] objectAtIndex:indexPath.row];
if (object[#"jsonUrl"]) {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:object[#"jsonUrl"] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSDictionary *tempObject = (NSDictionary *) responseObject;
if (![[responseObject objectForKey:#"type"] isEqualToString:#"error"]) {
NSDictionary *tempObject = [responseObject[#"data"] objectAtIndex:0];
cell.playingNow.text = tempObject[#"song"];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
cell.name.text = [NSString stringWithFormat:#" %#", object[#"title"]];
if (object[#"logoUrl"])
[cell.logo setImageWithURL:[NSURL URLWithString:object[#"logoUrl"]]];
}
I see that your problem is that you are fetching the data of you cells inside configureCommentCell that's called inside cellForRowAtIndexPath. which is wrong, because it too late to fetch data inside cellForRowAtIndexPath, in this delegate method you should return the cell.
this line may be called before retrieving the data from server :
cell.name.text = [NSString stringWithFormat:#" %#", object[#"title"]];
Instead you should:
Fetch the data inside a separate method for example fetchData
when the data is downloaded inside the completion block of AFNetworking method, store the data inside an NSArray called for example myDataArray still inside the completion block call [self.tableView reloadData];
In viewDidLoad method just call your method fetchData
And your cellForRowAtIndexPath should looks like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// hey please give me the cell to display ... harry up please
// please harry up ! oh my god you are fetching data from server
// while I am asking for the cell !
// ok I don't care do what you want
// I will return an empty cell anyway
// and guess what I will not take in consideration
// the retried data because it's inside a block
// which is called asynchronously
static NSString *cellIdentifier = #"radioCell";
RadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; }
// now before return the cell you need to update the content of cell
// maybe you have an array of items and you should update the label
// for example here and then return the cell
cell.usernameLabel = self.myDataArray[indexPath.row]; // example
return cell;
}
Well the TableView is reusing the cells, and you add the image every time a cell is displaid. Thus when reusing the cell you add an other image, but there already is an image.
You will have to reuse the image view, and only add the image if you create the cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifer = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer]autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20,0,30,44)];
imageView.tag = 1001;
[cell addSubview:imageView];
[imageView release], imageView= nil;
}
TabBarTestAppDelegate *delegate = (TabBarTestAppDelegate *)[[UIApplication sharedApplication] delegate];
NSArray *local = delegate.myData;
// ok, it's horrible, don't look at it :-)
cell.textLabel.text = [NSString stringWithFormat:#"%#%#", #" " ,[local objectAtIndex:indexPath.row]];
//
NSString* name = nil;;
if (indexPath.row == 0) {
name = #"topicon";
}
else if (indexPath.row + 1 == [local count]) {
name = #"bottomicon";
}
else {
name = #"innericon";
}
UIImageView *imageView = (UIImageView *)[cell viewWithTag:1001];
imageView.image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:name ofType:#"png"]];
return cell;
}

Loading thumbnail image in tableView

I have a UITableView within a UIViewController and I'm trying to load the imageFile as a thumbnail in my UITableViewCell. All UITableViewCell data is being loaded from parse and i can successfully load the NSObject name and username into the UITableViewCell but for some reason im getting an error with the thumbnial image. my code is as follows (for cell).
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return self.groups.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
PFObject *group = [self.groups objectAtIndex:indexPath.row];
PFFile *thumbnail = [group objectForKey:#"imageFile"];
PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
thumbnailImageView.layer.cornerRadius = thumbnailImageView.frame.size.width/2;
thumbnailImageView.layer.masksToBounds = YES;
thumbnailImageView.image = [UIImage imageNamed:#"cc"];
thumbnailImageView.file = thumbnail;
[thumbnailImageView loadInBackground];
UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [group objectForKey:#"name"];
UILabel *usernameLabel = (UILabel*) [cell viewWithTag:103];
usernameLabel.text = [group objectForKey:#"creatorName"];
return cell;
}
It seems that [cell viewWithTag:100] is a UIImageView in storyboard. Try to set the UIImageView class to PFImageView in identity inspector, hope this would solved your problem too.
Good luck
You are assigning object to PFFile:
The correct usage of PFFile is:
PFFile *thumbnail = [PFFile fileWithName:fileName data:fileData];
The correct usage of PFObject is:
PFObject *group = [PFObject objectWithClassName:#"your class name"];

Loading images in each section

I am currently using Parse as my back end and have a few photos stored on their servers. When I go to query them into my table view, every section comes up with the same image over and over again instead of having different images for each user. I will post my code for the cellForRowAtIndexPath I just don't understand what is going on. And each section has it's own header to display the user's name who posted the image.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger sections = self.userPhotos.count;
return sections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"cellIdentifier";
HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[HomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//Setting the image in the cell.
PFObject *carPhoto = [self.userPhotos objectAtIndex:indexPath.row];
PFFile *imageFile = [carPhoto objectForKey:#"imageFile"];
NSURL *imageFileUrl = [[NSURL alloc] initWithString:imageFile.url];
NSData *imageData = [NSData dataWithContentsOfURL:imageFileUrl];
cell.carImage.contentMode = UIViewContentModeScaleAspectFit;
cell.carImage.image = [UIImage imageWithData:imageData];
return cell;
}
Thank you for your help in advance!

Icon downloader downloads images only when UITableViewcell is outside screen.iPhone

I tried searching but did not find any solutions helpful.
I am using the following code for icons lazy loading.
The issue is, the icons are downloaded via lazy loading, but they are only seen once that particular cell is out of screen and is scrolled back into the screen.
I think it is some issue with dequeueReusableCellWithIdentifier but am not sure how to resolve it.
The images are downloaded alright, but are only visible in the cell once the cell goes out of screen.
// -------------------------------------------------------------------------------
// tableView:cellForRowAtIndexPath:
// -------------------------------------------------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableVw cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// customize the appearance of table view cells
//
static NSString *CellIdentifier = #"LazyTableCell";
static NSString *PlaceholderCellIdentifier = #"PlaceholderCell";
// add a placeholder cell while waiting on table data
NSUInteger nodeCount = [dataArray count];
if (nodeCount == 0 && indexPath.row == 0)
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
cell.detailTextLabel.text = #"Loading…";
return cell;
}
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor grayColor];
// Leave cells empty if there's no data yet
if (nodeCount > 0)
{
// Set up the cell...
AppRecord *appRecord = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = appRecord.appName;
cell.detailTextLabel.text = appRecord.artist;
// Only load cached images; defer new downloads until scrolling ends
if (!appRecord.appIcon)
{
if (tableView.dragging == NO && tableView.decelerating == NO)
{
[self startIconDownload:appRecord forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
cell.imageView.image = [UIImage imageNamed:#"Placeholder.png"];
}
else
{
cell.imageView.image = appRecord.appIcon;
}
}
return cell;
}
- (void)startIconDownload:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath
{
IconDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:indexPath];
if (iconDownloader == nil)
{
iconDownloader = [[IconDownloader alloc] init];
iconDownloader.appRecord = appRecord;
[iconDownloader setCompletionHandler:^{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// Display the newly loaded image
cell.imageView.image = appRecord.appIcon;
// Remove the IconDownloader from the in progress list.
// This will result in it being deallocated.
[imageDownloadsInProgress removeObjectForKey:indexPath];
}];
[imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
[iconDownloader startDownload];
}
}
- (void)loadImagesForOnscreenRows
{
if ([dataArray count] > 0)
{
NSArray *visiblePaths = [tableView indexPathsForVisibleRows];
for (NSIndexPath *indexPath in visiblePaths)
{
AppRecord *appRecord = [dataArray objectAtIndex:indexPath.row];
if (!appRecord.appIcon)
// Avoid the app icon download if the app already has an icon
{
[self startIconDownload:appRecord forIndexPath:indexPath];
}
}
}
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate)
{
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
I did code like following,
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:aURL
options:0
progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
{
if (image)
[aCell.imgViewThumb setImage:image];
else
[aCell.imgViewThumb setImage:[UIImage imageNamed:#"Dummy-image.jpg"]];
[aCell.indicator stopAnimating];
}];

Only Last Image Store in Array Get Display in Table view

My code below will produce the correct amount of data in array but the display data will only take the last value and display repeated.
For Example:
When i selected the first image then the first image is successfully display in table view.
When i selected the second image then the array will has 2 data but problem is in table view i will get 2 same image (the second selected image). My expected result will be when selected the second image the first image will still be there and the second display at the subsequence row.
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Collector in photoList %#",self.collector);
for (int i = 0; i < collector.count; i++) {
// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
CGImageRef iref = [imageRep fullResolutionImage];
if (iref) {
galleryImage = [UIImage imageWithCGImage:iref];
[self.tableView reloadData];
}
NSLog(#"[imageRep filename] : %#", [imageRep filename]);
};
NSLog(#"Collector %#",self.collector);
// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init];
[assetslibrary assetForURL:[collector objectAtIndex:i] resultBlock:resultblock failureBlock:nil];
}
- (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];
}
cell.imageView.image = galleryImage;
NSLog(#"Gallery image is %#",self.galleryImage);
return cell;
}
EDITED!
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Collector in photoList %#",self.collector);
for (int i = 0; i < collector.count; i++) {
// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
CGImageRef iref = [imageRep fullResolutionImage];
if (iref) {
galleryImage = [UIImage imageWithCGImage:iref];
//Added mutable array for galleryImage
[photoCollector addObject:galleryImage];
[self.tableView reloadData];
}
NSLog(#"[imageRep filename] : %#", [imageRep filename]);
};
NSLog(#"Collector %#",self.collector);
// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init];
[assetslibrary assetForURL:[collector objectAtIndex:i] resultBlock:resultblock failureBlock:nil];
}
- (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];
}
//Display image
if(photoCollector.count != 0)
{
cell.imageView.image = [self.photoCollector objectAtIndex:indexPath.row];
}
NSLog(#"This is in cellForRowAtIndexPath");
NSLog(#"Gallery image is %#",self.galleryImage);
// Configure the cell...
return cell;
}
EDITED code at picker didFinishPickingMediaWithInfo!!
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Initialize View Controller
PhotosListViewController *photoListViewController = [[PhotosListViewController alloc]initWithNibName:#"PhotosListViewController" bundle:nil];
ImageModel *imgModel = [[ImageModel alloc]init];
// get the ref url
imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
//set the imageUrl to the imageModel url in property ?
imgModel.url = imageURL;
[self.collector addObject:imageURL];
photoListViewController.urlCollector = self.collector;
NSLog(#"Collector in root %#",self.collector);
[picker dismissViewControllerAnimated:YES completion:nil];
[self.navigationController pushViewController:photoListViewController animated:YES];
}
EDITED FULL CODE!!
RootViewController.m
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Initialize View Controller
PhotosListViewController *photoListViewController = [[PhotosListViewController alloc]initWithNibName:#"PhotosListViewController" bundle:nil];
// get the ref url
imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
[self.collector addObject:imageURL];
photoListViewController.urlCollector = self.collector;
NSLog(#"Collector in root %#",self.collector);
[picker dismissViewControllerAnimated:YES completion:nil];
[self.navigationController pushViewController:photoListViewController animated:YES];
}
ImageModel.h
#import <Foundation/Foundation.h>
typedef void(^handler)(UIImage *image);
#interface ImageModel : NSObject
#property (nonatomic, strong) NSURL *imageUrl;
- (void)getImageWithCompletionHandler:(handler)completionBlock;
#end
ImageModel.m
#import "ImageModel.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AssetsLibrary/AssetsLibrary.h>
#implementation ImageModel
#synthesize imageUrl;
- (void)getImageWithCompletionHandler:(handler)completionBlock
{
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
CGImageRef iref = [imageRep fullResolutionImage];
if (iref) {
UIImage *image = [UIImage imageWithCGImage:iref];
completionBlock(image);
}
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init];
[assetslibrary assetForURL:self.imageUrl resultBlock:resultblock failureBlock:nil];
}
#end
PhotoListViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
test1 = [[UIImage alloc]init];
self.imageModelObjects = [NSMutableArray array];
for(NSURL *url in self.urlCollector)
{
ImageModel *imageModel = [[ImageModel alloc] init];
imageModel.imageUrl = url;
[self.imageModelObjects addObject:imageModel];
}
}
- (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];
}
ImageModel *model = [self.imageModelObjects objectAtIndex:indexPath.row];
[model getImageWithCompletionHandler:^(UIImage *image) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
});
}];
return cell;
}
#interface ViewController () <UITableViewDataSource>
#property (nonatomic, strong) NSMutableArray *images;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.images = [[NSMutableArray alloc] init];
NSLog(#"Collector in photoList %#",self.collector);
for (int i = 0; i < collector.count; i++) {
// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
CGImageRef iref = [imageRep fullResolutionImage];
if (iref) {
[self.images addObject:[UIImage imageWithCGImage:iref]];
[self.tableView reloadData];
}
NSLog(#"[imageRep filename] : %#", [imageRep filename]);
};
NSLog(#"Collector %#",self.collector);
// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init];
[assetslibrary assetForURL:[collector objectAtIndex:i] resultBlock:resultblock failureBlock:nil];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.images.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];
}
cell.imageView.image = self.images[indexPath.row];
return cell;
}
#end
Edited:
ImageModel.h
#import <Foundation/Foundation.h>
typedef void(^handler)(UIImage *image);
#interface ImageModel : NSObject
#property (nonatomic, strong) NSURL *imageURL;
- (void)getImageWithCompletionHandler:(handler)completionBlock;
#end
ImageModel.m
#import "ImageModel.h"
#implementation ImageModel
- (void)getImageWithCompletionHandler:(handler)completionBlock
{
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
CGImageRef iref = [imageRep fullResolutionImage];
if (iref) {
UIImage *image = [UIImage imageWithCGImage:iref];
completionBlock(image);
}
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc]init];
[assetslibrary assetForURL:self.imageURL resultBlock:resultblock failureBlock:nil];
}
Controller.m
#import "ViewController.h"
#import "ImageModel.h"
#interface ViewController ()
#property (nonatomic, strong) NSMutableArray *imageModelObjects;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageModelObjects = [NSMutableArray array];
for(NSURL *url in self.collector)
{
ImageModel *imageModel = [[ImageModel alloc] init];
imageModel.url = url;
[self.imageModelObjects addObject:imageModel]
}
//You can discard the collecter. IF u want the url, u can get from the self.imageModelObjects.
self.collector = nil;
}
- (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];
}
ImageModel *model = [self.imageModelObjects objectAtIndex:indexPath.row];
[model getImageWithCompletionHandler:^(UIImage *image) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
});
}];
// Configure the cell...
return cell;
}
if (iref)
{
galleryImage = [UIImage imageWithCGImage:iref];
//Added mutable array for galleryImage
[photoCollector addObject:galleryImage];
[photoCollector retain];
//[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"cell %d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text = #"Hello";
cell.imageView.image = [self.photoCollector objectAtIndex:indexPath.row];
}
// Configure the cell.
return cell;
}

Resources