How to load an image from JSON response? - ios

I am using the below code to load an image from json response and display the image in UICollectionView. But the numberofItems in Section count does return 0 . It means imageArray2.count returns 0. It does not work. Can anybody tell me where I am doing wrong in the below code? imageArray2 is my NSArray.
// JSON RESPONSE
claimImages = (
{
"image_url" = "http://zapponomics.net/claimservice/parcelimage/555506520image0.jpg";
"img_for" = "Front view of parcel";
"pro_number" = Rita;
}
);
images = (
{
"image_url" = "http://zapponomics.net/claimservice/parcelimage/384270647image0.jpg";
"img_for" = "Front view of parcel";
"pro_number" = Rita;
}
);
NSMutableDictionary *imageDict2 = [jsonDict valueForKey:#"claimImages"];
NSLog(#"Image Dictionary :- %#",imageDict2);
imageArray2 = [imageDict2 valueForKey:#"image_url"];
NSLog(#"My Array Image :- %#",imageArray2);
-(void)loadImageFromURL2:(NSURL *) url callback:(void(^)(UIImage *image1))callback
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSData *imageData1 = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(),^{
UIImage *image1 = [UIImage imageWithData:imageData1];
callback(image1);
});
});
}
if (collectionView.tag == 601)
{
cell = [afterParcelCollectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UIImageView *myImageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 80)];
myImageView2.tag = 102;
[cell.contentView addSubview:myImageView2];
NSString *myImage1= [imageArray2 objectAtIndex:indexPath.row];
[self loadImageFromURL2:[NSURL URLWithString:[myImage1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]] callback:^(UIImage *image1){
myImageView2.image =image1;
}];
}
return cell;

Try the following code and replace your code:
NSArray *claimImagesArray = [jsonDict valueForKey:#"claimImages"];
NSLog(#"%#", claimImagesArray);
NSString *imagePath = [[claimImagesArray objectAtIndex:0] valueForKey:#"image_url"];
NSLog(#"My Image :- %#", imagePath);

Related

Labels of UITableViewCells loading very slowly

As part of syncing phone to server, the phone takes data from API to populate tableview. Local placeholder images appear immediately and are replaced with remote images asynchronously. The problem is that the label for each row does not appear for up to twenty seconds until after the images have all downloaded even the label is a constant. How can I get labels to load more quickly?
-(void)configureCell:(IDItemCell *)cell withItem:(Items *)item {
[cell layoutIfNeeded];
//Label
cell.nameLabel.text = #"TEST LABEL";//does not load for 20 seconds
//image
NSString *picname = item.pic== nil ? #"" : item.pic;
cell.iconView.image = [UIImage imageNamed:#"placeholder.png"];//loads instantly
//remote fetch
if (item.pic !=nil) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: picname] ];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
cell.iconView.image =[self loadImageNamed:picname];
}
else {
NSString *picURL = [NSString stringWithFormat:#"https://www.~/pics/%#",picname];
dispatch_async(kBgQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:picURL]];
if (imgData) {
UIImage *imageFromWeb = [UIImage imageWithData:imgData];
if (imageFromWeb) {
[self saveImage:imageFromWeb asPicName:picname];
dispatch_async(dispatch_get_main_queue(), ^{
cell.iconView.image = imageFromWeb;
[cell setNeedsDisplay];
});
}
}
});
}
}
// Rounding the image view
cell.iconView.layer.cornerRadius = cell.iconView.frame.size.width / 2;
cell.iconView.clipsToBounds = YES;
cell.iconView.contentMode = UIViewContentModeScaleAspectFill;
}

Difficulty getting media to replace placeholder following download using JSQMessage

I'm using JSQMessage and am having a little difficulty with showing the placeholder for media until I have it correctly downloading, and then replacing with the media. I have everything working correctly as far as adding the messages and media to server, I just can't get it to replace the placeholders.
Currently, I have a function that queries my database and pulls an array of objects for messages and then loops through and calls this function for each object to output and add it to my message thread. I'm struggling to figure out why the section with "messageToAdd.isMediaMessage" is not replacing the placeholders with the actual media following it's download from the server. Does anyone know how I should be handling this to make sure it adds the message with a placeholder, and then replaces once the media is downloaded correctly?
- (void)addMessage:(PFObject *)object
{
id<JSQMessageMediaData> messageMedia = nil;
PFObject *user = object[#"messageSender"];
[users addObject:user];
NSString *name = #"";
if(user[#"profileFName"] && user[#"profileLName"])
name= [NSString stringWithFormat:#"%# %#",user[#"profileFName"],user[#"profileLName"]];
else
name= [NSString stringWithFormat:#"%# %#",user[#"consultantFName"],user[#"consultantLName"]];
if([object[#"messageFileType"] isEqual: #"video"]){
JSQVideoMediaItem *messageMedia = [[JSQVideoMediaItem alloc] init];
messageMedia.fileURL = nil;
messageMedia.isReadyToPlay = NO;
messageToAdd = [JSQMessage messageWithSenderId:user.objectId displayName:name media:messageMedia];
} else if ([object[#"messageFileType"] isEqual: #"image"]){
JSQPhotoMediaItem *messageMedia = [[JSQPhotoMediaItem alloc] init];
messageMedia.image = nil;
messageToAdd = [JSQMessage messageWithSenderId:user.objectId displayName:name media:messageMedia];
} else{
messageToAdd= [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object[#"sendDate"] text:object[#"messageContent"]];
}
if(isLoadMore)
[messages insertObject:messageToAdd atIndex:0];
else
[messages addObject:messageToAdd];
// NOT TRIGGERING THESE AFTER MEDIA DOWNLOADED
if (messageToAdd.isMediaMessage) {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
if ([object[#"messageFileType"] isEqual: #"image"]){
[object[#"messageMedia"] getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
JSQPhotoMediaItem *photoItem = [[JSQPhotoMediaItem alloc] initWithImage:[UIImage imageWithData:imageData]];
((JSQPhotoMediaItem *)messageMedia).image = [UIImage imageWithCGImage:photoItem.image.CGImage];
[self.collectionView reloadData];
}
}];
}
else if([object[#"messageFileType"] isEqual: #"video"]){
PFFile *videoFile = object[#"messageMedia"];
NSURL *videoURL = [NSURL URLWithString:videoFile.url];
((JSQVideoMediaItem *)messageMedia).fileURL = videoURL;
((JSQVideoMediaItem *)messageMedia).isReadyToPlay = YES;
[self.collectionView reloadData];
}
else {
NSLog(#"%s error: unrecognized media item", __PRETTY_FUNCTION__);
}
});
}
}
For others who come along with the same issue/question, I resolved how it was working by looking at the project NotificationChat here:https://github.com/relatedcode/NotificationChat/blob/master/NotificationChat/Classes/Chat/ChatView.m. It gives a really good overview of using the JSQMessage platform.
Here's my modified function so you can see the finished product.
- (void)addMessage:(PFObject *)object
{
PFObject *user = object[#"messageSender"];
[users addObject:user];
PFFile *mediaMessage = object[#"messageMedia"];
NSString *name = #"";
if(user[#"profileFName"] && user[#"profileLName"])
name= [NSString stringWithFormat:#"%# %#",user[#"profileFName"],user[#"profileLName"]];
else
name= [NSString stringWithFormat:#"%# %#",user[#"consultantFName"],user[#"consultantLName"]];
if([object[#"messageFileType"] isEqual: #"video"]){
JSQVideoMediaItem *mediaItem = [[JSQVideoMediaItem alloc] initWithFileURL:[NSURL URLWithString:mediaMessage.url] isReadyToPlay:YES];
mediaItem.appliesMediaViewMaskAsOutgoing = [user.objectId isEqualToString:self.senderId];
messageToAdd = [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object.createdAt media:mediaItem];
} else if ([object[#"messageFileType"] isEqual: #"image"]){
JSQPhotoMediaItem *mediaItem = [[JSQPhotoMediaItem alloc] initWithImage:nil];
mediaItem.appliesMediaViewMaskAsOutgoing = [user.objectId isEqualToString:self.senderId];
messageToAdd = [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object.createdAt media:mediaItem];
[mediaMessage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
if (error == nil)
{
mediaItem.image = [UIImage imageWithData:imageData];
[self.collectionView reloadData];
}
}];
} else{
messageToAdd= [[JSQMessage alloc] initWithSenderId:user.objectId senderDisplayName:name date:object[#"sendDate"] text:object[#"messageContent"]];
}
if(isLoadMore)
[messages insertObject:messageToAdd atIndex:0];
else
[messages addObject:messageToAdd];
}
Based on the code I think one possible reason is you need reloadData on main(UI) thread after download data successfully and asynchronously on background thread

Matching items in two arrays iOS

I have two arrays, one with usernames and the other with played games, I want to match the profile picture that is in the username array to the yourName in played games however I cannot seem to get it to work.
for(id object in self.playedGames){
PFObject *obb = object;
for(int l = 0; l <self.Userarray1.count;l++){
if([[obb objectForKey:#"yourName"]isEqual:[[self.Userarray1 valueForKey:#"username"]objectAtIndex:l]] ){
PFFile *imageFile = [[self.Userarray1 valueForKey:#"profilePic"]objectAtIndex:l];
if(imageFile !=nil){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSURL* imageFileUrl = [[NSURL alloc] initWithString:imageFile.url];
NSData *imageData = [NSData dataWithContentsOfURL:imageFileUrl];
UIImage *newImageset = [UIImage imageWithData:imageData];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
UIImageView *imgVew = [[UIImageView alloc] initWithFrame:CGRectMake(4, 5, 50, 50)];
imgVew.image = newImageset;
imgVew.opaque = YES;
[ImageArray addObject:imgVew];
NSLog(#"imageArray count = %i",ImageArray.count);
if(ImageArray.count == self.playedGames.count){
[self getStuff];
}
});
});
}
else{
UIImage *NoPP = [UIImage imageNamed:#"friends_tab.png"];
NoPP = [self imageScaledToSize:CGSizeMake(50, 50)withImage:NoPP];
UIImageView *NoPPView = [[UIImageView alloc]initWithFrame:CGRectMake(4, 5, 50, 50)];
NoPPView.image = NoPP;
NoPPView.opaque = YES;
[ImageArray addObject:NoPPView];
}
}
}
}
Realized that i was doing asynchronous work and synchronous work so the ImageArray was being added at different times so I fixed it with this solution
if(imageFile !=nil){
UIImageView *imgVew = [[UIImageView alloc]initWithFrame:CGRectMake(4, 5, 50, 50)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSURL* imageFileUrl = [[NSURL alloc] initWithString:imageFile.url];
NSData *imageData = [NSData dataWithContentsOfURL:imageFileUrl];
UIImage *newImageset = [UIImage imageWithData:imageData];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
imgVew.image = newImageset;
imgVew.opaque = YES;
});
});
[ImageArray addObject:imgVew];
NSLog(#"imageArray count = %i",ImageArray.count);
if(ImageArray.count == self.playedGames.count){
[self getStuff];
}
}
it also made iterating through that function faster as well

How to implement endless loading in table or collection view?

I’m building an article reading app. I’m fetching data from JSON link like article image and title in uitableview.
I’m unable to implement pagination in uitableview, let say my JSON link is www.example.com&page=1 contain 10 articles at a time which is 1-10.
When I concatenate in the JSON link like www.example.com&page=2 to get 11-20 article list.
I’m unable to implement how I can load the data in uitableview on scrolling and increase no.of rows with data.
Here is my code:
int *x=1;
int *inc=10;
#interface ysTableViewController ()
{
Reachability *internetReachable;
}
#end
#implementation ysTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self checkInternetConnection];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,10,0,20)];
titleLabel.textColor = [UIColor blackColor];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.text = #"Story";
[self.navigationItem setTitleView:titleLabel];
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
CGPoint offset = aScrollView.contentOffset;
CGRect bounds = aScrollView.bounds;
CGSize size = aScrollView.contentSize;
UIEdgeInsets inset = aScrollView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
float reload_distance = 10;
if(y > h + reload_distance) {
NSLog(#"load more rows");
inc=inc+10;
BOOL myBool = [self isNetworkAvailable];
if (myBool)
{
#try {
// for table cell seperator line color
self.tableView.separatorColor = [UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:1.0];
// for displaying the previous screen lable with back button in details view controller
UIBarButtonItem *backbutton1 = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStyleBordered target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:backbutton1];
_Title1 = [[NSMutableArray alloc] init];
_Author1 = [[NSMutableArray alloc] init];
_Images1 = [[NSMutableArray alloc] init];
_Details1 = [[NSMutableArray alloc] init];
_link1 = [[NSMutableArray alloc] init];
_Date1 = [[NSMutableArray alloc] init];
NSString *urlString=[NSString stringWithFormat:#“www.example.com&page=%d",x];
NSLog(#"xxxxx===%d",x);
NSURL *newUrl=[NSURL URLWithString:urlString];
NSData* data = [NSData dataWithContentsOfURL:newUrl];
NSArray *ys_avatars = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
x++;
if(ys_avatars){
for (int j=0;j<ys_avatars.count;j++)
{
[_Title1 addObject:ys_avatars[j][#"title"]];
[_Author1 addObject: ys_avatars[j][#"author"]];
[_Images1 addObject: ys_avatars[j][#"featured_img"]];
[_Details1 addObject:ys_avatars[j][#"content"]];
[_link1 addObject:ys_avatars[j][#"permalink"]];
NSString *newStr=[ys_avatars[j][#"date"] substringToIndex:[ys_avatars[j][#"date"] length]-3];
[_Date1 addObject:newStr];
} }
else
{
NSLog(#"asd");
} }
#catch (NSException *exception) {
}
}
}
}
- (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 inc;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier1 = #"ysTableViewCell";
ysTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];
// Configure the cell...
long row = [indexPath row];
cell1.TitleLabel1.text = _Title1[row];
cell1.AuthorLabel1.text = _Author1[row];
NSString *yourStoryUrl = [_Images1[indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
if(yourStoryUrl) {
NSArray *subStringsUrl = [yourStoryUrl componentsSeparatedByString:#"/"];
NSString *stripedName = [subStringsUrl lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Local stored image file path
NSString* filePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",stripedName]];
if(filePath) {
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
if(image) {
// Now the image will have been loaded and decoded and is ready to rock for the main thread
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=image;
cell1.ThumbImage1.image=image;
} else {
dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(taskQ, ^{
NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl];
NSData *data = [NSData dataWithContentsOfURL:Imageurl];
UIImage *images1 = [[UIImage alloc] initWithData:data];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(images1);
//_imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",stripedName]];
// NSLog((#"pre writing to file"));
if (![imageData writeToFile:filePath atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
NSLog((#"the cachedImagedPath is %#",filePath));
}
// Now the image will have been loaded and decoded and is ready to rock for the main thread
dispatch_sync(dispatch_get_main_queue(), ^{
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=images1;
cell1.ThumbImage1.image=images1;
});
});
}
} else {
dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(taskQ, ^{
NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl];
NSData *data = [NSData dataWithContentsOfURL:Imageurl];
UIImage *images1 = [[UIImage alloc] initWithData:data];
// NSString *myString = [Imageurl absoluteString];
// NSLog(#"%#",myString);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(images1);
_imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",stripedName]];
// NSLog((#"pre writing to file"));
if (![imageData writeToFile:_imagePath atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
// NSLog((#"the cachedImagedPath is %#",_imagePath));
}
// Now the image will have been loaded and decoded and is ready to rock for the main thread
dispatch_sync(dispatch_get_main_queue(), ^{
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=images1;
cell1.ThumbImage1.image=images1;
});
});
}
}
return cell1;
}
This is by no means easy. IN GENERAL TERMS you need code that looks like this..
Note the four very distinct parts of this fundamental routine.
I have never found a working "general" package solution for this problem.
Again, look to the "four sections" in this: they give the logic you're looking for!
-(void)forTerm:(NSString *)term doPageAfter:(int)doingThisPage
{
doingThisPage = doingThisPage + 1;
if ( doingThisPage > 20 ) return; // never, ever, ever forget that!! heh.
[CLOUD search:term page:doingThisPage then:^(NSArray *thoseTenResults)
{
self.searchSpinner.hidden = YES;
// (step 1) IF IT IS "PAGE 1", we need to re-kick-off the array...
if ( doingThisPage == 1 )
CLOUD.searchResultsRA = [[NSMutableArray alloc] init];
// (step 2) go ahead and add on these results
if ( doingThisPage == 1 )
{
[CLOUD.searchResultsRA addObjectsFromArray:thoseTenResults];
[self.searchDisplay safelyReloadBouncyTable];
}
else
{
[self.searchDisplay.collectionView performBatchUpdates:^
{
NSUInteger oldSize = CLOUD.searchResultsRA.count;
[CLOUD.searchResultsRA addObjectsFromArray:thoseTenResults];
NSUInteger newSize = CLOUD.searchResultsRA.count;
NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
for (NSUInteger i = oldSize; i < newSize; i++)
[arrayWithIndexPaths
addObject:[NSIndexPath indexPathForRow:i inSection:0]];
[self.searchDisplay justSignal];
[self.searchDisplay.collectionView
insertItemsAtIndexPaths:arrayWithIndexPaths];
}
completion:nil];
}
// (step 3) indeed if it's the first page, do a drop-in for fun
if ( doingThisPage == 1 ) [self.searchDisplay.view dropIn:nil];
// (for a "new search" which is now being displayed, in your UX
// there would be some sort of indication of that fact - do it here)
// (step 4) IF there WERE results .. try another page!
if ( thoseTenResults.count > 0 )
[self forTerm:term doPageAfter:doingThisPage];
// note we are calling this same routine, again!!!
}
];
}

Conditionally Add Cell Data to NSMutable Array

Having a lot of trouble with this today. Finally decided to turn to the experts.
I have a standard Table View Controller. Each cell has a built-in UIImage with a tap gesture recognizer that toggles the image back and forth from a green checkmark to a red x. That's working just fine.
What I'm trying to do now is write a conditional statement that says: When the image is a green checkmark, add the cell textLabel to the saved NSMutableArray; else remove red x objects from the array (that may have been added at an earlier time). Currently I'm getting "null" in the console on both accounts.
Here's the original method:
-(void)imageTapped:(UIGestureRecognizer*)gesture
{
UIImageView *selectedImageView=(UIImageView*)[gesture view];
UIImage *imageRed = [UIImage imageNamed:#"checkmark(red).png"];
UIImage *imageGreen = [UIImage imageNamed:#"checkmark(green).png"];
NSString *address = #" ";
NSString *name = #" ";
UITableViewCell *cell = [self.placesTableView cellForRowAtIndexPath:self.placesTableView.indexPathForSelectedRow];
name = cell.textLabel.text;
address = cell.detailTextLabel.text;
NSMutableArray *saved = [[NSMutableArray alloc] initWithObjects:#"%#",#"%#", name, address, nil];
NSString *csv = [NSString stringWithFormat:#"%#, %#", name, address];
if (selectedImageView.image == imageGreen) {
selectedImageView.image = imageRed;
[saved removeObject:csv];
NSLog(#"Deselected" #"%#", name);
} else {
selectedImageView.image = imageGreen;
[saved addObject:csv];
NSLog(#"Selected" #"%#", name);
}
}
EDITED: Suggested method (still not working):
h: #property (strong, nonatomic) NSMutableArray *saved;
m:
- (void)viewDidLoad
{
_saved = [[NSMutableArray alloc] init];
}
-(void)imageTapped:(UIGestureRecognizer*)gesture
{
UIImageView *selectedImageView=(UIImageView*)[gesture view];
UIImage *imageRed = [UIImage imageNamed:#"checkmark(red).png"];
UIImage *imageGreen = [UIImage imageNamed:#"checkmark(green).png"];
NSString *address = #" ";
NSString *name = #" ";
UITableViewCell *cell = [self.placesTableView cellForRowAtIndexPath:self.placesTableView.indexPathForSelectedRow];
name = cell.textLabel.text;
address = cell.detailTextLabel.text;
NSString *csv = [NSString stringWithFormat:#"%#, %#", name, address];
self.saved = [NSMutableArray array];
//NSData *imageRedData = UIImagePNGRepresentation(imageRed);
NSData *imageGreenData = UIImagePNGRepresentation(imageGreen);
NSData *selectedImageViewData = UIImagePNGRepresentation(selectedImageView.image);
if ( [selectedImageViewData isEqual: imageGreenData]) {
selectedImageView.image = imageRed;
[self.saved removeObject:csv];
NSLog(#"Deselected" #"%#", name);
} else {
selectedImageView.image = imageGreen;
[self.saved addObject:csv];
NSLog(#"Selected" #"%#", name);
}
}
Do you mean to create the saved mutable array every time? It won't persist past the end of the imageTapped method. Perhaps you want this NSMutableArray to be a property (or ivar) and add-to or remove from self.saved?
you need to change the UIImage comparison logic, instead of using = operator use isEqual method on NSObject. Here is a solution code which help you.
-(void)imageTapped:(UIGestureRecognizer*)gesture
{
UIImageView *selectedImageView=(UIImageView*)[gesture view];
UIImage *imageRed = [UIImage imageNamed:#"checkmark(red).png"];
UIImage *imageGreen = [UIImage imageNamed:#"checkmark(green).png"];
NSString *address = #" ";
NSString *name = #" ";
UITableViewCell *cell = [self.placesTableView cellForRowAtIndexPath:self.placesTableView.indexPathForSelectedRow];
name = cell.textLabel.text;
address = cell.detailTextLabel.text;
NSMutableArray *saved = [[NSMutableArray alloc] initWithObjects:#"%#",#"%#", name, address, nil];
NSString *csv = [NSString stringWithFormat:#"%#, %#", name, address];
NSData *imageRedData = UIImagePNGRepresentation(imageRed);
NSData *imageGreenData = UIImagePNGRepresentation(imageGreen);
NSData *selectedImageViewData = UIImagePNGRepresentation(selectedImageView.image);
if ( [selectedImageViewData isEqual: imageGreenData]) {
selectedImageView.image = imageRed;
[saved removeObject:csv];
NSLog(#"Deselected" #"%#", name);
} else {
selectedImageView.image = imageGreen;
[saved addObject:csv];
NSLog(#"Selected" #"%#", name);
}
}

Resources