Saving image to Documents directory and retrieving for email attachment - ios

I having trouble figuring out NSBundle & DocumentDirectory data, I have a Camera Picture "imageView" that I'm saving to the NSDocumentDirectoy and then want to retrieve it for attaching to an email,
Here the saving code:
- (IBAction)saveImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
Here is the new getting data code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"savedImage"];

- (IBAction)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
}
This should get you started!

Swift 3
// Create a URL
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let imageURL = documentsURL?.appendingPathComponent("MyImageName.png")
// save image to URL
let myImage = imageView.image! // or wherever you have your UIImage
do {
try UIImagePNGRepresentation(myImage)?.write(to: imageURL!)
} catch {}
// Use the URL to retrieve the image for sharing to email, social media, etc.
// docController.URL = imageURL
// ...
I force unwrapped some of the optionals for brevity. Use guard or if let in your code.

Because each iPhone app is in it's own sandbox, you don't have access to a device-wide documents folder. To attach an image to an email, save the image in your own documents folder. Try using [#"~/Documents" StringByExpandingTildeInPath] to get your local documents folder - that works for me. It looks like the technique you're using for attaching the image to an email is correct.
Hope that helps,

Try this one :
-(void)setProfilePic
{
NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [docpaths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"Image.png"];
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:imagePath]];
UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
[profilePic_btn setBackgroundImage:thumbNail forState:UIControlStateNormal];
}

Related

How to fetch multiple images from server and save and show them in iPhone app?

I am using following code for getting single image. But, how to do it for multiple images?
This is my code :
-(void)viewDidLoad
{
[super viewDidLoad];
[self performSelectorInBackground:#selector(loadImageIntoMemory) withObject:nil];
}
-(void)loadImageIntoMemory {
NSLog(#"Beginning download");
NSString *temp_Image_String = [[NSString alloc] initWithFormat:#"http://www.thewavestore.com/appproductimage/"];
NSURL *url_For_Ad_Image = [[NSURL alloc] initWithString:temp_Image_String];
NSData *data_For_Ad_Image = [[NSData alloc] initWithContentsOfURL:url_For_Ad_Image];
UIImage *temp_Ad_Image = [[UIImage alloc] initWithData:data_For_Ad_Image];
[self saveImage:temp_Ad_Image];
UIImageView *imageViewForAdImages = [[UIImageView alloc] init];
imageViewForAdImages.frame = CGRectMake(0, 0, 320, 480);
imageView.image = [self loadImage];
[self.view addSubview:imageView];
}
-(void)saveImage:(UIImage *)image {
NSLog(#"Saving");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent: #"DSC02077129HT41.5W20L24WT18.555RS28775.jpg" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
-(UIImage *)loadImage {
NSLog(#"Got the data!");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"DSC02077129HT41.5W20L24WT18.555RS28775.jpg" ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
Please help to over come from this issues,if any good idea please suggest me.
First save your images with unique names (i am using current time) and save this names to an array
NSData *imageData = UIImagePNGRepresentation(chosenImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
// save image with currentdate and time in the name
NSString * imageName = [NSString stringWithFormat:#"name_%#.png",[dateFormatter stringFromDate:[NSDate date]]];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
//add all the images names to the imagepath array
[imagePathArray addObject:imageName];
//write image into file
[imageData writeToFile:fullPathToFile atomically:YES];
then retrive images from image path array
for (NSString*path in imagePathArray ) {
NSArray *filepart = [path componentsSeparatedByString:#"."];
NSString *filename = [filepart objectAtIndex:0];
NSString *extension = [filepart objectAtIndex:1];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/%#",
documentsDirectory,path];
//NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData *fileData = [NSData dataWithContentsOfFile:fileName];
}
1. Store the server images in to array.
NsMutableArray *arrImages=[[nsmutableArray alloc]init];
2.Get the count of the array to run this in for loop.
for(int i=0;i<[arrImages count];i++)
{
NSLog(#"Saving");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent: arrImages[i]];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
To convert it to JPEG
NSData=UIImageJPEGRepresentation(UIImage,1.0);

UIImages not recovered Once Device is Restarted

In iOS 8, I am writing UIImages on the device using the code
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *pathString = [NSString stringWithFormat:#"%#/%#%ld",documentsDirectory, #"ProfileImage", (long)[[NSUserDefaults standardUserDefaults] integerForKey:#"PatientsId"]];
NSData *imageData = UIImageJPEGRepresentation(image, 40);////I have replaced it with UIImagePNGRepresentation as well
[imageData writeToFile: pathString atomically:YES];
The write to file is successful.
If I try to recover the image using the function,
NSArray *documentDirectories =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
// Get one and only document directory from that list
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
NSString *pathString =[documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#%ld", #"ProfileImage", (long)[[NSUserDefaults standardUserDefaults] integerForKey:#"PatientsId"]]] ;
UIImage *image = [UIImage imageWithContentsOfFile: pathString];
The image is recovered.
However, if I restart the device, the images are not there anymore. The function [UIImage imageWithContentsOfFile: pathString] returns nil and if I use NSData *myData = [[NSData alloc] initWithContentsOfFile: pathString];, the myData is nil as well.
This procedure was working perfectly fine prior to iOS 8, however, it isn't working properly anymore. Can someone please guide me what is wrong with this?

How to get path of the image choose from gallery in iPhone?

I have Five buttons.On each button action.I have open gallery and choose an image.But the problem is on each button action same path is coming.
UIImage* image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
NSData* imageData = UIImagePNGRepresentation(image);
NSString * imageName = #"Myimage.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"fullPathToFile=%#",fullPathToFile); //important line
[imageData writeToFile:fullPathToFile atomically:NO];
Set global variable initially int countVal = 1;
NSString * imageName = [NSString stringWithformat:#"%d.png",countVal]; // Imgae_name set here
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"fullPathToFile=%#",fullPathToFile); //important line
[imageData writeToFile:fullPathToFile atomically:NO];
count +=1; // Increment count here
I may be missing something, but it looks like you're using the same name for the image each time: Myimage.png. Every time the image will be saved inside the documents directory with that same name. Maybe add a tag to each button and use that to distinguish each of the 5 different images?
May be it will helpful for u
[picker dismissModalViewControllerAnimated:YES];
imageView.image= [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *webData = UIImagePNGRepresentation(imageView.image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:png];
[webData writeToFile:localFilePath atomically:YES];
NSLog(#"localFilePath.%#",localFilePath);
UIImage *image = [UIImage imageWithContentsOfFile:localFilePath];
OR
Use this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
imageView.image= [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *webData = UIImagePNGRepresentation(imageView.image);
[imageData writeToFile:savedImagePath atomically:NO];
NSLog(#"localFilePath.%#",localFilePath);
If you still get it empty then try by checking if NSData is created properly
NSLog(#"webData.%#",webData);
OR
Try this: I hope defnetly it will be be helpful to you
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
//you can use UIImagePickerControllerOriginalImage for the original image
//Now, save the image to your apps temp folder,
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:#"upload-image.tmp"];
NSData *imageData = UIImagePNGRepresentation(img);
//you can also use UIImageJPEGRepresentation(img,1); for jpegs
[imageData writeToFile:path atomically:YES];
//now call your method
[self uploadMyImageToTheWebFromPath:path];
}
Try to use below code which just edited to you answer
The problem is only with saving image name,try to save it with different name
The below code will help you in saving image with diffrent name
note: put the tag value to diffrent button(5 buttons) and call bello method in its target
-(void)saveImage:(UIButton*)sender{
UIImage* image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
NSData* imageData = UIImagePNGRepresentation(image);
NSString * imageName =[NSString stringWithFormat:#"Myimage%d.png",sender.tag];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"fullPathToFile=%#",fullPathToFile); //important line
[imageData writeToFile:fullPathToFile atomically:NO];
}
by this you can save image with different name

How can I add more images in NSDocumentDirectory?

First I stored image path from web service into SQLITE, and then I retrieve it back using local path. I am using NSMutableArray. I've successfully stored one image in NSDocumentDirectory, but I have one issue, How can I store more than one images in NSDocumentDirectory?
My code is,
if ([[[node childAtIndex:counter] name] isEqualToString:#"Column5"])
{
NSString *str = [[node childAtIndex:counter] stringValue];
[Col5 addObject:str];
NSString *myString = [Col5 componentsJoinedByString:#","];
NSString *aString = [NSString stringWithFormat:#"http://webserviceurl/%#",myString];
NSURL *url= [NSURL URLWithString:aString];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:strCol4];
UIImage *image = tmpImage;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
For this line:
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:strCol4];
Just use a different path component.

Download from protected with password FTP server with use of CFNetwork

I am making an app that can dowload from FTP server that protected with username and password file and saved it in documentsDirectory. I have managed to download file directly from HTTP, save and dispaly it. Now I wish to do so from FTP. Here is my code:
-(IBAction)download:(id)sender
{
NSString *stringURL = #"http://www.image.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename3.png"];
[urlData writeToFile:filePath atomically:YES];
}
}
-(IBAction)viewImage:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"filename3.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
[imageV setImage:img];
}
Can anyone please point me to CFNetwork example. I need to connect to ftp server, list files in folder and download them. Already looked at http://developer.apple.com/library/ios/#Documentation/Networking/Conceptual/CFNetwork/CFFTPTasks/CFFTPTasks.html#//apple_ref/doc/uid/TP30001132-CH9-SW1 but it`s not so clear.
Consider using BlackRaccoon to work with FTP.

Resources