UIButton's IBAction only works the first time it is tapped - ios

Using Apple's template "Tabbed Bar Banner" I found that the button in one of the views only works the first times I pressed it.
If the iPhone is connected to Xcode to run the app, it works great. Once I have detached the cable, the button stops working.
- (IBAction)sendData:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.allowsEditing = YES;
[self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:^{
[self openEmail];
}];
}
-(IBAction) openEmail {
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
[mailComposer setMailComposeDelegate:self];
if ([MFMailComposeViewController canSendMail]) {
[mailComposer setToRecipients:[NSArray arrayWithObjects:#"*******", nil]];
[mailComposer setSubject:self.nameTextField.text];
NSLog(#"self.nameTextField.text = %#", *********);
[mailComposer setMessageBody:#"******r" isHTML:NO];
[mailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Answer" ofType:#"plist"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[mailComposer addAttachmentData:myData mimeType:#"application/xml" fileName:#"Answer.plist"];
NSData *imageData = UIImageJPEGRepresentation(selectedImage, 0.5);
[mailComposer addAttachmentData:imageData mimeType:#"image/jpg" fileName:[NSString stringWithFormat:#"%#.jpg",*********]];
[self composeCSV];
NSString *fileName = [file lastPathComponent];
[mailComposer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:fileName];
[self presentViewController:mailComposer animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)composeCSV{
NSMutableString *mainString = [[ NSMutableString alloc]initWithString:#"++;++;++;++;...\n"];
[mainString appendFormat:#"%#;\n",...];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
file = [NSString stringWithFormat:#"%#/%#.csv",documentsDirectoryPath,******];
NSError *csVerror= NULL;
BOOL written = [mainString writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&csVerror];
if (!written) {
NSLog( #"Writing failed, error = %#",csVerror);
}else {
NSLog(#"Data saved! File path = %#",file);
}
}

Related

Sending a email with pdf attachment from documents directory Objective c

I am having issues getting my program to accept the path I gave it and returning it as NSData
// Get the resource path and read the file using NSData
NSString *searchFilename = #"SafetyAuditReport.pdf"; // name of the PDF you are searching for
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
}
NSLog(#"found %#", documentsSubpath);
}
NSData *pdfData = [NSData dataWithContentsOfFile:documentsSubpath];
// Determine the MIME type
NSString *mimeType = #"application/pdf";
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[mc addAttachmentData:pdfData mimeType:mimeType fileName:#""];
NSLog(#"data was loaded.......");
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:nil];
When ever the program gets the the emailing section it throws a nil exception for addAttachmentData:pdfData mimeType:mimeType fileName: saying the variable I gave it was nil (pdfData) when I know the file exists in the documents directory.
Thanks in advance
plz use this code
- (IBAction)sendMailWithAttachedFile
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.pdf"];
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:path];
NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
[picker addAttachmentData:data mimeType:#"application/pdf" fileName:#"data.pdf"];
[self presentModalViewController:picker animated:YES];
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
Here is how we did it.....
NSString *path = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
path = [[NSBundle mainBundle]pathForResource:#"Name of File" ofType:#"pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:path];
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.editing = YES;
mail.mailComposeDelegate = self;
[mail setSubject:#"Your subject"];
[pdfData writeToFile:path atomically:NO];
[mail addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"Name OF File.pdf"];
[self presentViewController:mail animated:YES completion:NULL];

How to show and play captured photos and videos,Audios in ios [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi i am beginner in Ios and in my project i have given facility for users capturing photos and videos and Audios from camera and i am storing their "paths" in array lists and i am displays them in one table-list so for everything is ok
But here my main requirement is when i click table-list rows then if there is image file it must be shows or if there is video it must be play audio also have to play as like videos for this i have written some code here photos and videos are playing fine but audio files giving problem what did i do here wrong?
my code:-
#import "ViewController2.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController2 ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
AVAudioRecorder * _audioRecorder;
AVAudioPlayer * player;
}
#end
#implementation ViewController2
#synthesize maintablelist;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
maintablelist.delegate = self;
maintablelist.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
- (IBAction)takeAudio:(id)sender {
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSetting
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
}
else {
NSLog(#"ok");
[arr_media addObject:soundFilePath];
[_audioRecorder record];
[maintablelist reloadData];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[maintablelist reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[maintablelist reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
}
#end
Here, I have modified your piece of code. First of all, there is no need of different arrays to store images and videos. You can access it from one. Simillarly, there is no need of storing media types in two different arrays. You can do it by one array.
Moreover, to save images and videos to document directory, you need to write those file to specific path. You will then be able to access them.
#import "ViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#interface ViewController ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
}
#end
#implementation ViewController
#synthesize tbl;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
tbl.delegate = self;
tbl.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
-(IBAction)takeAudio
{
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[arr_media addObject:soundFilePath];
[_audioRecorder record];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
//UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//
// NSString *Dir = [paths objectAtIndex:0];
// NSString *fileName = [NSString stringWithFormat:#"Pic-%lf.png", [[NSDate date] timeIntervalSince1970]];
//
// //this path if you want save reference path in sqlite
// NSString *pngPath = [NSString stringWithFormat:#"%#/%#",Dir,fileName];
//
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[tbl reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[tbl reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
// NSString*thePath=[[NSBundle mainBundle] pathForResource:[arr_media objectAtIndex:indexPath.row] ofType:#"MOV"];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
#end
Your issue is that you are not saving the captured images/photos and simply trying to use the paths. Please take a look at Apple Documentation on how to use it. You can save them in your project's Documents directory, save the file name and path as you are doing then use those paths for rendering/playing later on.
As a side note, in your implementation, there are few lines of code that you are executing after [picker dismissViewControllerAnimated:YES completion:nil]. I would advise to utilize completion block here and load your table view once image picker view dismissal is complete. This avoid run time crashes.
EDIT: On OP request
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #“image1.png”];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[imageData writeToFile: filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:^{
// Save your model data and reload table here
}];
}
}

How do I email a pdf using the MFMailComposeViewContoller?

I have a pdf file called FlashCards.pdf
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
NSArray *recipients = #[#"aarone_2010#hotmail.com"];
// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:#"FlashCards" ofType:#"pdf"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"application/pdf" fileName:#"FlashCards"];
[picker setSubject:#"Flashcards"];
[picker setToRecipients:recipients];
[picker setMessageBody:#"Hello" isHTML:NO];
[picker setMailComposeDelegate:self];
[self presentViewController:picker animated:YES completion:nil];
[self dismissViewControllerAnimated:YES completion:nil];
The email is being sent and it seems that everything is working, but it's not sending the PDF file.
EDIT:
This actually works, I had other problems in other parts of my code. My problem is solved. I also made sure that the extensions were correct instead of having FlashCards as a file name, it should be FlashCards.pdf This is the exact code I have working:
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
NSArray *recipients = #[#"android.aaron.david#gmail.com"];
NSString *path = [[NSBundle mainBundle] pathForResource:#"FlashCards" ofType:#"pdf"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"application/pdf" fileName:#"FlashCards.pdf"];
[picker setSubject:#"Flashcards"];
[picker setToRecipients:recipients];
[picker setMessageBody:#"Hello" isHTML:NO];
[picker setMailComposeDelegate:self];
[self presentViewController:picker animated:YES completion:nil];
Use MIME type text/x-pdf instead of application/pdf. Also check the size/length of myData to verify that the PDF was loaded.

iOS: file name in email attachment

I can send a .csv file as an attachment from my app, but I'd like to shorten the name file for that attachment, because there will be a pile of csv files delivered to the recipient.
Piece of code:
...
if (dorsalesPorTramoYcontrol && dorsalesPorTramoYcontrol.count )
{
NSMutableString *mainString = [[ NSMutableString alloc]initWithString:#"dorsal,paso,tiempo\n"];
for (NSManagedObject *get in dorsalesPorTramoYcontrol) {
//dorsales
NSString *string =[get valueForKey:#"dorsal"];
[mainString appendFormat:#"%#,",string];
//paso
string = [get valueForKey:#"paso"];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
[mainString appendFormat:#"%#,",string];
//tiempo
string = [get valueForKey:#"tiempo"];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
[mainString appendFormat:#"%#",string];
[mainString appendFormat:#"\n"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
file = [NSString stringWithFormat:#"%#/Tramo%#Control%#.csv", documentsDirectoryPath,section,control];
NSError *csVerror= NULL;
BOOL written = [mainString writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&csVerror];
if (!written) {
NSLog( #"Writing failed, error = %#",csVerror);
}else {
NSLog(#"Data saved! File path = %#",file);
[self composeEmail];
}
}
}
-(void)composeEmail{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:[NSString stringWithFormat:#"Resultados Tramo: %# - Control: %#", section, control]];
NSArray *toRecipients = [NSArray arrayWithObjects:#"somebodymail#mail.com", nil];
[mailer setToRecipients:toRecipients];
// Logo
UIImage *myImage = [UIImage imageNamed:#"logo.png"];
NSData *imageData = UIImagePNGRepresentation(myImage);
[mailer addAttachmentData:imageData mimeType:#"image/png" fileName:#"Icon"];
[mailer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:file];
NSString *emailBody =
[NSString stringWithFormat:#"Resultados Tramo: %# - Control: %# \nDorsal - Paso - Tiempo", section, control];
[mailer setMessageBody:emailBody isHTML:NO];
mailer.modalPresentationStyle = UIModalPresentationPageSheet;
[self presentViewController:mailer animated:YES completion:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Your device doesn't support the composer sheet"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}
}
The filename is the following:
<_var_mobile_Applications_BE8CE610-A83E-4C79-8B9C-0263FA6881D6_Documents_Tramo2Control4.csv>
and I'd like it to be just "Tramo2Control4.csv"
Could you please offer some suggestions to get it?
Change the following line:
[mailer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:file];
To:
NSString *fileName = [file lastPathComponent];
[mailer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:fileName];
You were originally setting the file name to be the entire file path.

Attach an image to an email

I was wondering if there is a way to allow the user to select an image from the camera roll, and then attach it to an email?
Here is the code I have now:
-(IBAction) openEmail {
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
[mailComposer setMailComposeDelegate:self];
if ([MFMailComposeViewController canSendMail]) {
[mailComposer setToRecipients:[NSArray arrayWithObjects:#"TPsecondary_Example#email.com", nil]];
[mailComposer setSubject:#"Learning Trail Submission"];
[mailComposer setMessageBody:emailbody isHTML:NO];
[mailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Answer" ofType:#"plist"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[mailComposer addAttachmentData:myData mimeType:#"application/xml" fileName:#"Answer.plist"];
[self presentModalViewController:mailComposer animated:YES];
}
}
There sure is!
In your .h file add these delegates and declare a UIImage named selectedImage.
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
Then in your .m you can add the following.
Link -(IBAction)openImagePicker:(id)sender to the button that you want to start the process.
- (IBAction)openImagePicker:(id)sender
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:^{
[self openEmail];
}];
}
-(IBAction) openEmail {
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
[mailComposer setMailComposeDelegate:self];
if ([MFMailComposeViewController canSendMail]) {
[mailComposer setToRecipients:[NSArray arrayWithObjects:#"TPsecondary_Example#email.com", nil]];
[mailComposer setSubject:#"Learning Trail Submission"];
[mailComposer setMessageBody:emailbody isHTML:NO];
[mailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Answer" ofType:#"plist"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[mailComposer addAttachmentData:myData mimeType:#"application/xml" fileName:#"Answer.plist"];
NSData *imageData = UIImageJPEGRepresentation(selectedImage, 1.0);
[mailComposer addAttachmentData:imageData mimeType:#"image/jpg" fileName:#"imageTitle"];
[self presentModalViewController:mailComposer animated:YES];
}
}
EDIT: Mind you this is a very basic example that doesn't handle events such as the user selecting a video instead of an image...

Resources