Passing a UIImage from a viewcontroller to another - ios

I want to pass a UIImage from a View Controller to another one, but it doesn't work. I actually get (null) if I log the UIImage Value in the second View Controller.
The Image File comes from parse.com. And it works absolutely fine in the first view controller. But as soon as I pass it to the second view controller, the image won't work there.
Here's the code:
My prepareForSegue in the .m file of the firstViewController (BookListTableViewController)
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"ShowBookDetailSegue"]) {
NSIndexPath *indexPath = [self.bookListTableView indexPathForSelectedRow];
ParseBookDetailTableViewController *pbdtvc = segue.destinationViewController;
PFObject *tempObject = [totalStrings objectAtIndex:indexPath.row];
PFFile *eventImage = [tempObject objectForKey:#"bookImage"];
if(eventImage != NULL)
{
[eventImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
pbdtvc.bookImageDetail = thumbnailImage;
}];
}
my .h file of the secondViewController (ParseBookDetailViewController)
#property (strong, nonatomic) UIImage* bookImageDetail;
#property (strong, nonatomic) IBOutlet UIImageView *bookImageDetailView;
viewDidLoad of my .m file of the secondViewController (ParseBookDetailViewController)
NSLog(#"%#",bookImageDetail);
[bookImageDetailView setImage:bookImageDetail];
As I said: in the original View Controller the Image is correct. I can log it and even set it there to an ImageView. But in the second view controller there is (null).
Glad for help, thanks..
EDIT:
This is the code from my cellForRowAtIndexPath.
PFObject *tempObject = [totalStrings objectAtIndex:indexPath.row];
//cell.textLabel.text = [tempObject objectForKey:#"bookTitle"];
cell.titleTextField.text = [tempObject objectForKey:#"bookTitle"];
cell.bookAutor1Label.text = [tempObject objectForKey:#"bookAutor1"];
cell.isbnLabel.text = [tempObject objectForKey:#"bookISBN"];
cell.statusLabel.text = [tempObject objectForKey:#"bookStatus"];
cell.yearLabel.text = [tempObject objectForKey:#"BookDate"];
if ([cell.statusLabel.text isEqualToString:#"nicht verfügbar"]) {
cell.statusLabel.tintColor = [UIColor redColor];
cell.dotImageIcon.image = [UIImage imageNamed:#"dot_red.png"];
}else if ([cell.statusLabel.text isEqualToString:#"verfügbar"]){
cell.statusLabel.tintColor = [UIColor greenColor];
cell.dotImageIcon.image = [UIImage imageNamed:#"dot_green.png"];
}
PFFile *eventImage = [tempObject objectForKey:#"bookImage"];
if(eventImage != NULL)
{
[eventImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
prepareForSegueImage = thumbnailImage;
[cell.bookImageView setImage:thumbnailImage];
}];
}
At the bottom I have set the Image (that works) in a new property (prepareForSegueImage). NOW its loaded.
And now I've tried to pass only the prepareForSegueImage to the new view controller, but it actually doesn't pass the one from the cell, it passes the last one loaded in the whole table view from the first view controller.

I'm guessing:
[eventImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error)
{
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
pbdtvc.bookImageDetail = thumbnailImage;
}];
is an asynchronous request happening in the background, that will take some time to return. But your code is expecting it to happen instantly.
Load the image first and call the segue in the completion block,
EDIT
If it works in the first viewController (meaning you have the image) why are you requesting it again? why not simply pass the image you already have?
EDIT 2:
As explained in my comment, your variable is being overwritten each time the cellForRowAtindexPath is called. You could either wrap that code in an if statement, checking for an index or a certain image etc. or you can use the below code to get a specific cell and pull the image form that.
[tblView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:2 inSection:0]];
If you have the image downloaded and have a relatively easy means of getting a reference to it you should not be downloading it again. This could cost the user on a 3G data plan as well as waste resources.

This happens because you are using the getDataInBackgroundWithBlock, which is an asynchronous call. As this happens in a background thread, it is probably not finished when you segue to the other viewcontroller.
You said it works fine in the first controller. I assume this means you have already downloaded the image. Put that in a property instead, and send this property to the next controller.

Related

Multiple NSURLSessions Causing UITableView Problems

I'm running into a bit of a strange problem here. One of my NSURLSessions is in charge of getting information for restaurant information that I have stored (restaurant name, restaurant's logo URL, etc), and then the second NSURLSession is in charge of using the restaurant's logo URL to retrieve the specific image and set it for each UITableView's cell.
The problem, however, is that my UITableView does not load anything at all sometimes so the cells are empty, but at other times when I add an extra [_tableView reload] in the NSURLSessions' completion block in the fetchPosts method, it'll work, but then the cells will stop displaying anything again if I re-run it. Something is definitely wrong. Have a look at my code below:
#import "MainViewController.h"
#import "SWRevealViewController.h"
#import "RestaurantNameViewCell.h"
#import "RestaurantList.h"
#interface MainViewController ()
#end
#implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//List of restaurants needed to load home page
_restaurantInformationArray = [[NSMutableArray alloc] init];
self.tableView.dataSource = self;
self.tableView.delegate = self;
//setup for sidebar
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sidebarButton setTarget: self.revealViewController];
[self.sidebarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
//Get list of restaurants and their image URLs
[self fetchPosts];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_restaurantInformationArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RestaurantNameViewCell *cell = (RestaurantNameViewCell *)[_tableView dequeueReusableCellWithIdentifier:#"restaurantName" forIndexPath:indexPath];
RestaurantList *currentRestaurant = [_restaurantInformationArray objectAtIndex:indexPath.row];
cell.restaurantName.text = currentRestaurant.name;
cell.imageAddress = currentRestaurant.imageURL;
cell.restaurantClicked = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapDetected:)];
cell.restaurantClicked.numberOfTapsRequired = 1;
cell.restaurantLogo.userInteractionEnabled = YES;
[cell.restaurantLogo addGestureRecognizer:cell.restaurantClicked];
cell.restaurantLogo.tag = indexPath.row;
//Add restaurant logo image:
NSString *URL = [NSString stringWithFormat:#"http://private.com/images/%#.png",cell.imageAddress];
NSURL *url = [NSURL URLWithString:URL];
NSURLSessionDownloadTask *downloadLogo = [[NSURLSession sharedSession]downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
cell.restaurantLogo.image = downloadedImage;
}];
[downloadLogo resume];
return cell;
}
-(void)fetchPosts {
NSString *address = #"http://localhost/xampp/restaurants.php";
NSURL *url = [NSURL URLWithString:address];
NSURLSessionDataTask *downloadRestaurants = [[NSURLSession sharedSession]dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *someError;
NSArray *restaurantInfo = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&someError];
for(NSDictionary *dict in restaurantInfo) {
RestaurantList *newRestaurant = [[RestaurantList alloc]init];
newRestaurant.name = [dict valueForKey:#"name"];
newRestaurant.imageURL = [dict valueForKey:#"image"];
[_restaurantInformationArray addObject:newRestaurant];
//Refresh table view to make sure the cells have info AFTER the above stuff is done
[_tableView reloadData];
}
}];
[downloadRestaurants resume];
}
#end
It's probably a very stupid mistake that I'm making, but I'm not certain how I should correct this. I'm new to iOS development, so would greatly appreciate some guidance :)
Besides assuming that your network requests aren't erroring (you should at least log if there are network errors), there are threading issues.
Your NSURLSession callback probably runs on a background thread. This makes it unsafe to call UIKit (aka - [_tableView reloadData]). UIKit isn't thread safe. This means invoking any of UIKit's APIs from another thread creates non-deterministic behavior. You'll want to run that piece of code on the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
Likewise for fetching the images. It's slightly more complicated because of table view cell reuse which could cause the wrong image to display when scrolling. This is because the same cell instance is used for multiple values in your array as the user scrolls. When any of those callbacks trigger, it'll replace whatever image happens to be in that cell. The generally steps to reproduce this is as follows:
TableView requests 5 cells
MainViewController requests 5 images (one for each cell)
User scrolls down one cell
The first cell gets reused as the 6th cell.
MainViewController requests another image for the 6th cell.
The 6th image is retrieved, the callback is triggered, image of the first cell is set to image #6.
The 1st image is retrieved, the callback is triggered, image of the first cell is set to image #1 (incorrect).
You'll need to make sure the cell is displaying the correct cell before attempting to assign the image to it. If you rather not implement that logic for image fetching in cells, you could use SDWebImage instead. Using SDWebImage's [UIImageView sd_setImageWithURL:] is thread safe (it will set the image on the main thread).
Side notes:
You only need to reload data once all your changes are in _restaurantInformationArray, and not every time in the for loop.

image on cell memory warning

(Xcode 5,ios7,arc)i have a view controller,it have a tableview,The problem is that cell loading picture, make a memory leak. I have repeatedly push the view controller ,and then back, memory continues to increase. My English is not good, do not know whether the clear expression. How to solve the problem of excessive picture memory, hope to master for help.Here is the code:
#implementation SearchCell
-(void)dealloc
{
_imageV = nil;
_titleL = nil;
_infoL = nil;
_countL = nil;
}
+(instancetype) cellWithTableView:(UITableView *)tableView model:(SearchModel *)model
{
static NSString* strID = #"SPECIALCELL";
SearchCell* cell = [tableView dequeueReusableCellWithIdentifier:strID];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"SearchCell" owner:nil options:nil] lastObject];
}
[cell setSearchCellModel:model];
return cell;
}
-(void) setSearchCellModel:(SearchModel*)model
{
UIImage* img = [[SDWebImageManager sharedManager] imageWithURL:[NSURL URLWithString:model.tvImgURL]];
self.imageV.image = img;
self.titleL.text = model.tvName;
self.infoL.text = model.tvInfo;
self.countL.text = model.tvCount;
}
hear
you get the your answer for this question ... you need to use lasy loading image view..
i would like to give hint for that.
1). first you need to save image on document directory unique name(url name) then check if image are there in document directory then you fetch image from document directory folder and when you save image that time you save image small size use this link code easily solve your problem.

Parse data image shows in iOS simulator but not in device

I'm using a collection view controller to show thumbnails. Click on the thumbnail and a segue opens to the full image modally. It works fine on the simulator, but not on my iphone or ipad. The full image is blank. The "comment" shows up in all devices.
Here's the segue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showBandPhoto"]) {
NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
BDBPhotoViewController *destViewController = segue.destinationViewController;
NSIndexPath *indexPath = [indexPaths objectAtIndex:0];
PFObject *tempObject = [imageObjectsArray objectAtIndex:indexPath.row];
PFFile *imageFile = [tempObject objectForKey:#"image"];
NSData *imageData = [imageFile getData];
UIImage *image = [UIImage imageWithData:imageData];
destViewController.bandImageName = image;
NSLog(#"image is %#", image);
NSString *commentGet = [tempObject objectForKey:#"comment"];
destViewController.comment = commentGet;
Here's the code for the photo controller viewDidLoad:
self.photoImageView.image = bandImageName;
self.commentLabel.text = comment;
Instead of using UIImageView, try using a PFImageView. This subclass makes it much easier for loading image data directly from Parse.
I'm not sure why this worked, but I moved the retrieval from Parse to viewDidLoad and created the image array there. When the segue is called it gets the image from the array, rather than having to query Parse.
For me the problem was that I added extension in image naming. The simulator could read the image but not the device. when I removed extension it worked.
Furthermore, as explained in this post:
images in iphone app appear in simulator but not when compiled to device
Mac file system is case-insensitive and iOS file system is case sensitive. Your problem is maybe juste due to image naming.

Having trouble passing NSString from plist to ImageView

I'm currently using a plist to populate my table view rows(i.e. Name, Description and Image). When the user selects a row, a new controller is pushed up with an imageView presenting the rows image in full screen.
The problem that I'm facing is, passing the string to the new viewController's imageView.
All the NSLog's return the correct information, except that when it logs the UIImageView, it returns null then. Am I not connecting it correctly? The row doesn't display any image until it's selected (essentially the row is acting, similar to a thumbnail).
Any help would be greatly appreciated thank you!!!
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *childDictionary = [mainChildren objectAtIndex:indexPath.row];
//Image Name NSString from plist
childImage = [childDictionary objectForKey:#"Child Image"];
if ([childDictionary objectForKey:#"Child Image"] == nil) {
NSLog(#"No Image String Found.");
}
else {
NSLog(#"Image String Found. Image Name is: %#", childImage);
UIImage *myImage = [UIImage imageNamed:childImage];
NSLog(#"Image Found. Image is: %#", myImage);
UIImageView *childImageView = [childImageView setImage:myImage];
NSLog(#"ImageView Found. ImageView is: %#", childImageView);
FullscreenImageViewController *imgViewer = [[FullscreenImageViewController alloc] init];
imgViewer.fullScreenImageView = childImageView;
[self presentViewController:imgViewer animated:YES completion:nil];
}
}
When you instantiate a new UIImageView, it should be [[UIImageView alloc] initWithImage:image].
Or since your full screen image controller has property of image view, e.g. fullScreenImageView, you can just set the image of the property directly with a UIImage instance.

Parse.com image gallery open image detail view

I haven't been programming for very long and I am trying to create a simple image gallery using Parse.com, I have followed this tutorial https://www.parse.com/tutorials/saving-images but using storyboards instead of nibs.
I managed to got most of it working but I'm stuck at the last hurdle, when it comes to opening the selected image full size in a new view.
Following other answers given around the web I have tried to pass the image to the detail view in - (void)prepareForSegue: but I'm still having no luck.
My code in ViewController.h currently looks like this
- (void)buttonTouched:(id)sender {
PFObject *theObject = (PFObject *)[allImages objectAtIndex:[sender tag]];
PFFile *theImage = [theObject objectForKey:#"imageFile"];
NSData *imageData;
imageData = [theImage getData];
selectedPhoto = [UIImage imageWithData:imageData];
[self performSegueWithIdentifier:#"goGo" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([[segue identifier] isEqualToString:#"goGo"]) {
PhotoDetailViewController *pdvc = [[PhotoDetailViewController alloc] init];
pdvc.selectedImage = selectedPhoto;
}
}
and in DetailViewController.h
- (void)setDetailImage {
self.photoImageView.image = selectedImage;
}
When it comes to loading the image the view opens blank, any help on this would be a massive help. If it makes it easier I can upload the project.
Thanks in advance,
Chris
Your actual prepareForSegue statements does nothing : you're initializing selectedImage to a totally new PhotoDetailViewController but not the one which will be presenting.
Try to replace
PhotoDetailViewController *pdvc = [[PhotoDetailViewController alloc] init];
by
PhotoDetailViewController *pdvc = (PhotoDetailViewController *)segue.destinationController;

Resources