i am storing images as base64 NSData in database and getting from Database and display in UICollectionView cellForItemAtIndexPathas cell.bgImageView.imageimages are displaying but scrolling is not smooth and when i am trying to get back from another ViewController its taking too much time to load the view.
CODE
NSData *imageData=[[NSData alloc]initWithBase64EncodedString:itemObj.strImage options:NSDataBase64DecodingIgnoreUnknownCharacters];
cell.bgImageView.image = [UIImage imageWithData:imageData];
Code
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
ItemViewController *vc = [[ItemViewController alloc]initWithNibName:#"ItemViewController" bundle:nil];
vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
Item *itemObject = [[Item alloc]init];
itemObject = [arrayOfItems objectAtIndex:indexPath.item];
vc.strItemName = itemObject.strItemName;
vc.strItemDesc = itemObject.strShortDescription;
vc.strImage = itemObject.strImage;
[self presentViewController:vc animated:YES completion:nil];}
above is the code for next viewController and passing values and iam come back to CollectionView like this
- (void)dismiss{
[self dismissViewControllerAnimated:YES completion:nil];
}
If you are setting image as below,
[UIImage imageWithData:data]
this is synchronous operation, so it will block your main thread until it finishes loading.
THis is the reason why your scroll view is jerky because you blocked the main thread.
Try loading the images in backGround Thread, it will definitely solve ur problem.
Code for loading in backGround thread,
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:#"www.example.com"]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.myImageView.image = image;
});
});
Put your iimage loading code in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
your code here....
});
Related
The user is able to click a button to download a set of maps, upon completion of that task, I would like to hide the progress indicator. I have tried several variants of the below code but have not achieved what I am searching for. Any guidance would be appreciated.
- (IBAction)SavePhotoOnClick:(id)sender{
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSURL *url = [NSURL URLWithString:urlstr1];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
});
// Set determinate mode
HUD.mode = MBProgressHUDModeDeterminate;
HUD.dimBackground = YES;
HUD.color = [UIColor colorWithRed:0.23 green:0.50 blue:0.82 alpha:0.90];
HUD.delegate = self;
HUD.labelText = #"Downloading Maps";
// myProgressTask uses the HUD instance to update progress
[HUD showWhileExecuting:#selector(myProgressTask) onTarget:self withObject:nil animated:YES];
}
- (void)myProgressTask {
// This just increases the progress indicator in a loop
float progress = 0.0f;
while (progress < 1.0f) {
progress += 0.01f;
HUD.progress = progress;
usleep(40000);
}
}
Removing the progresstask method and the showWhileExecuting code removes the progress indicator. It seems that usleep overrides everything and does not allow for the progress indicator to be hidden after the download completes and instead removes it after the 4 sec.
Your problem is that myProgressTask doesn't perform any actual work: your download actually happens in your dispatch_async call. Use a call like [hud showHUDAddedTo: self.navigationController.view animated:YES]; before you start your network request, so it will become hidden when your download completes. This will only show the spinning indicator, not a progress circle.
If you want the progress circle, you will need to use NSURLConnection and its associated delegate methods to track the progress of the download. Specifically, look at the connection:didReceiveResponse: method—using the expectedContentLength to calculate the percentage, using values you get from the connection:didReceiveData: method to incrementally update this progress.
Check out this question for an example of how to do this.
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.
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;
In my app, I am loading images for UITableViewCells asynchronously like this:
-(void) loadImage:(NSString *)urlString cell:(UITableViewCell *)cell {
UIImageView *iv = cell.imageView;
UIImage *image = [imageCache objectForKey:urlString];
if(!image) {
NSURL *url = [NSURL URLWithString:urlString];
image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if(image) {
[imageCache setObject:image forKey:urlString];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
iv.image = image;
[cell addSubview:iv];
});
}
When the tableview is refreshed before all of the images have finished loading, an exception is thrown on iv.image = image; because iv has been deallocated. What is the best way to make sure I never try to set an image for a deallocated cell? Is there some way to kill any lingering asynchronous loads when the tableview is reloaded?
I would implement this other way around. Try to get an image from cache when you are constructing the cell. If the image is not found trigger on asynchronous download and notify cell or controller (from main thread) that image was downloaded. You can use KVO to connect cells with images cache.
Now I'm using this code, with a little modification:
if (self._photoPath && !self._photo) {
dispatch_queue_t bg_thread = dispatch_queue_create("com.yourcompany.bg_thread", NULL);
dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_async(bg_thread,^{
NSData *data = [NSData dataWithContentsOfFile:self._photoPath];
if(data != nil) {
dispatch_async(main_queue,^{
self._photo = [UIImage imageWithData:data];
[self.photoButton setImage:[UIImage imageNamed:#"photoButton.png"] forState:UIControlStateNormal];
});
}
});
}
As you can see, in fact after I get that photo I want set it immediately to my "photoButton",
but now, UI got smoothed, but my photoButton's appearance is always black...
What should I do next?
Thanks for your patience.
_______________Updated________
I have 2 viewControllers, A and B.
A is the root viewController, and B is A's child viewController.
In B, there is a button for calling the camera to take a photo.
After user toke a photo, the photo's apperance becomes that photo.
When I push a new B (with no photo) from A,
things goes smoothly.
But when there is an old B with a photo in it.
the animation gets a little stucked, since the following code I guess:
- (void)viewWillAppear:(BOOL) animated {
if (self._photoPath && !self._photo) {
NSData *data = [NSData dataWithContentsOfFile:self._photoPath];
if(data != nil)
self._photo = [UIImage imageWithData:data];
}
[super viewWillApear];
}
But I do need to get that photo before the view is displayed since I need to set that photo to my photoButton's background.
So, is there a way to avoid stucking the view's animation? Cause it really result in bad user experience.
Thanks a lot!
I found the answer.
Just add a line of code to refresh the button.
For me, it is
[self.photoButton setImage:[UIImage imageNamed:#"photoButton.png"] forState:UIControlStateNormal];
NSUInteger p[2] = {1,4};
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:
[NSIndexPath indexPathWithIndexes:p length:2]]
withRowAnimation:UITableViewRowAnimationNone];