Image not loading correctly in app - ios

My app lets the user select the photo from camera roll or take the photo, the app saves the photo locally and then goes to the next view controller and loads the image that was just saved and displayed on an image view.
This is the code that I used to get the image the user wanted and sent it to my send picture method.
UIImage *image = info[UIImagePickerControllerEditedImage];
[self saveImage:image];
[picker dismissViewControllerAnimated:NO completion:NULL];
[self performSegueWithIdentifier:#"switch" sender:nil];
Which is this:
-(void)saveImage: (UIImage*)image{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"test.png"];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
printf("image saved");
}
That code ran because it printed the image was saved. The app goes to the next view and this is how I set up my viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
//[imageViewPreview setImage:self.secondImage];
//imageViewPreview.image = self.secondImage;
}
I commented out both ways that I've tried but neither of those works. This is how I was trying to get my secondImage to load:
-(UIImage* )secondImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"test.png"];
UIImage* image = [UIImage imageWithContentsOfFile:path];
printf("image loaded");
return image;
}
what is wrong here?

You should do this much simpler. In your second view controller add a public UIImage property. Then import the second controller into the first one. Then in prepareForSegue set it the image like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"switch"]) {
ClassOfDEstinationController *destinationController = segue.destinationViewController;
destinationController.image = image;
}
}

Related

Share an Image and Text on WhatsApp in IOS programmatically?

I am to add an image and some text in whatsapp with the help of coding. How can I perform it to solve my problem?
You can post Image or Text on WhatsApp. But you wont post both at a time becouse whatsapp not provide any API that you can add caption and post image with text.
Following is an example for posting image from iPhone app to whatsapp as par WhatsApp Documentation:
in ViewController.h file:
#interface ViewController : UIViewController
{
}
#property(nonatomic,retain) UIDocumentInteractionController *documentationInteractionController;
in ViewController.m file:
- (IBAction)bocClick:(UIButton *)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"]; //here i am fetched image path from document directory and convert it in to URL and use bellow
NSURL *imageFileURL =[NSURL fileURLWithPath:getImagePath];
NSLog(#"imag %#",imageFileURL);
self.documentationInteractionController.delegate = self;
self.documentationInteractionController.UTI = #"net.whatsapp.image";
self.documentationInteractionController = [self setupControllerWithURL:imageFileURL usingDelegate:self];
[self.documentationInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL
usingDelegate: (id ) interactionDelegate {
self.documentationInteractionController =
[UIDocumentInteractionController interactionControllerWithURL: fileURL];
self.documentationInteractionController.delegate = interactionDelegate;
return self.documentationInteractionController;
}

Can't load images from "Documents" folder in iPhone/iPhone Simulator

I have a part which is supposed to save an image into my phone's "Documents" folder and then access it. It saves fine, but the load methods don't really work. Here's my .m code:
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:
#"photo.png" ];
UIImage *image = [UIImage imageWithContentsOfFile:path];
return image;
studentImage = [[UIImageView alloc] initWithImage: image]; //UIImageView property
}
- (UIImage*)loadBarcode
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"barcode.png" ];
NSLog(#"%#", path);
UIImage *image = [UIImage imageWithContentsOfFile:path];
return image;
barcode = [[UIImageView alloc] initWithImage: image]; // UIImageView property
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadBarcode];
[self loadImage];
}
The files are definitely there to access, the file paths are correct. But the UIImageViews I'm trying to assign them to come up blank. I'm running out of options. Do you guys have any suggestions as to what it might be?
In loadImage method, the problem is here:
return image;
studentImage = [[UIImageView alloc] initWithImage: image];
You first use return statement which transfers the control and never assign it to the UIImageView control.
It should be something like:
studentImage = [[UIImageView alloc] initWithImage: image];
return image;
One more point, if studentImage is connected through IB, DON'T re-allocate it. Instead use:
studentImage.image = image;
Hope it helps!
Problem is fixed now, was an issue with my property names, but thank you for helping me clean up my code!

Writing/loading to/from file

Im trying to learn how to save/load images, and i just don't get why this wont work. Im writing a screenshot to the filesystem like this:
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directories objectAtIndex:0];
NSString *key = [documentsDirectory stringByAppendingPathComponent:#"screenshots.archive"];
[data writeToFile:key atomically:YES];
And in the "init" medthod in my UITableView subclass, i do this:
pics = [[NSMutableDictionary alloc]initWithContentsOfFile:[self dataFilePath]];
dataFilePath method:
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"screenshots.archive"];
}
To test if this works i have this delegate method:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return pics.count;
}
I test it by taking a screenshot, and then initializing my UITableview subclass, but it show no rows. What am i doing wrong?
There are a few key issues with the code that are causing it to not work. You're storing the image data directly to the file and trying to read it back as a dictionary. You'll want to wrap the image in an array first, and write the array to the file. Then you'll want to read the file into an array for the table to display. To sum up the changes:
Change
[data writeToFile:key atomically:YES];
to
NSMutableArray *storageArray = [NSMutableArray arrayWithContentsOfFile:key];
if(!storageArray)
storageArray = [NSMutableArray arrayWithObject:data];
else
[storageArray addObject:data];
[storageArray writeToFile:key atomically:YES];
and change
pics = [[NSMutableDictionary alloc]initWithContentsOfFile:[self dataFilePath]];
to
pics = [[NSArray alloc] initWithContentsOfFile:[self dataFilePath]];

Data passing of photo taken in App

I used the code
-(IBAction)TakePhoto {
picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:nil];
[self performSegueWithIdentifier:#"CropImage" sender:sender];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
//obtaining saving path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"latest_photo.png"];
//extracting image from the picker and saving it
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];
}
}
- (void)imagePickerControllerDidCancel :(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"CropImage"])
{
CropImageViewController *cropImageViewController = segue.destinationViewController;
cropImageViewController.theImage = yourImage;
// Similar to [segue.destinationViewController setTheImage:yourImage];
}
}
I have a problem here using the storyboard. I have multiple view controllers in the storyboard. I have the camera button (which the user can take the photo in app) on the first view controller. However I want to pass the data of the photo that the user took in the first view controller to another view controller automatically so that the user can crop it and then save it into a "directory or something"(did not decide yet).
update
I am having now four errors currently saying
http://tinypic.com/view.php?pic=15q6y3b&s=5
Click the image it will be bigger
Actually, you don't have to pass the photo directly to the next view since you had already saved it. You can simply read back the image from the same file in the target view controller. (This method is better if the view controllers are not close to one another.)
+ (UIImage *)readImageFromFile:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"latest_photo.png"];
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
return [UIImage imageWithData:imageData];
}
UPDATED: You can also pass the photo using property though.
In your target view controller (I will name it CropImageViewController), in .h,
#property (nonatomic, retain) UIImage *theImage;
In the "getPhoto" view controller, on top of the page,
#import "CropImageViewController.h"
In imagePickerController,
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
...
// This line should be
[self performSegueWithIdentifier:#"CropImage" sender:self];
}
In prepareForSegue method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"CropImage"])
{
CropImageViewController *cropImageViewController = segue.destinationViewController;
cropImageViewController.theImage = yourImage;
// Similar to [segue.destinationViewController setTheImage:yourImage];
}
}
Make sure you set a name, e.g. "CropImage", for the segue identifier in storyboard.

Saving an Image in App Directory instead of going to photo album. Objective C iOS

Hello I have an app that takes pictures but doesn't save. I know how to save the image to the Photo Album but I need the image to go to the app's directory and will not show up in the Photos gallery. I already have searched and I failed to look for a working one. I also need that image to be in my UIImageView when I open my app. Here are my codes:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *picker;
UIImagePickerController *picker2;
UIImage *image;
IBOutlet UIImageView *imageView;
}
-(IBAction)TakePhoto;
-(IBAction)ChooseExisting;
- (IBAction)btnSave:(id)sender;
- (IBAction)btnLoad:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)TakePhoto{
picker = [[UIImagePickerController alloc]init];
picker.delegate=self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];
// [picker release];
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImage.png"] ];
image = [UIImage imageWithContentsOfFile:path];
return image;
}
-(IBAction)ChooseExisting{
picker2 = [[UIImagePickerController alloc]init];
picker2.delegate=self;
[picker2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker2 animated:YES completion:NULL];
// [picker release];
}
- (IBAction)btnSave:(id)sender {
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImage.png"]];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#"saved");
}
}
- (IBAction)btnLoad:(id)sender {
[self loadImage];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)viewDidLoad
{
[self loadImage];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
The Save and loadImage methods don't work :(. No idea why but I don't have any errors.
Your image saving/loading code seems correct.
Check if your IBActions are properly connected in IB.
And change:
- (IBAction)btnLoad:(id)sender
{
[self loadImage];
}
to:
- (IBAction)btnLoad:(id)sender
{
[self loadImage];
[imageView setImage:image];
}
Your original code seems to load the image but it doesn't show it anywhere.
EDIT:
You can always check if the image is saved to documents directory.
With the device connected open the organizer window in XCode.
Select your device, then select applications. Choose the application
you're interested in and you should see the file-tree related to that
app. Is your image file listed in the Documents folder?
Check in documents directory for image. Your calling [self loadImage]; but loadImage return UIImage which your not using anywhere. You can attach data to picker like the following.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"MyImage.png"];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
[picker2 addAttachmentData:myData mimeType:#"image/png" fileName:#"MyImage"];

Resources