attachment not sent with email from ipad - xcode

I have an iPad that has a routine to create a pdf and send as an attachment to an email. It all seems to work with the email composer opening showing the pdf document attached. However when tested on an iPad, when the email is received there is no attachment. Any ideas?
[mailComposer addAttachmentData:data mimeType:#"application/pdf" fileName:#"pdffile.pdf"];
[self presentViewController:mailComposer animated:YES completion:nil];
Many thanks
Detail:
The pdf file is created and called pdffile.pdf. The following is the full email routine:
MFMailComposeViewController *mailComposer;
mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setModalPresentationStyle:UIModalPresentationFormSheet];
[mailComposer setSubject:[NSString stringWithFormat: #"i-observe Lesson Observation for: %s", "date"]];
[mailComposer setMessageBody:[NSString stringWithFormat: #"i-observe Lesson Observation for: %s", "name"] isHTML:NO];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingFormat:#"pdffile.pdf"];
NSMutableData *data=[NSMutableData dataWithContentsOfFile:file];
[mailComposer addAttachmentData:data mimeType:#"application/pdf" fileName:#"pdffile.pdf"];
[self presentViewController:mailComposer animated:YES completion:nil];

Try This Method:
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mail=[[MFMailComposeViewController alloc]init];
mail.mailComposeDelegate=self;
[mail setSubject:#"Email with attached pdf"];
NSString *newFilePath = #"get path where the pdf reside";
NSData * pdfData = [NSData dataWithContentsOfFile:newFilePath];
[mail addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"yourpdfname.pdf"];
NSString * body = #"";
[mail setMessageBody:body isHTML:NO];
[self presentModalViewController:mail animated:YES];
[mail release];
}
else
{
NSLog(#"Message cannot be sent");
}

The next solutions is based assuming that the pdf file is in your main bundle:
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *myFile = [mainBundle pathForResource: #"RealNameofFile" ofType: #"pdf"];
NSData *pdfD = [NSData dataWithContentsOfFile:myFile];
[mailViewController addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"Nametodisplayattached.pdf"];

make sure that the file has the same name as the table cell

Related

NSManagedObject : having one answer of a loop instead of multiple answer from a loop Xcode

i have a problem when creating a txt file from a for statement. Here is the code of the statement on a CoreData.
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * allTickets = [[NSFetchRequest alloc] init];
[allTickets setEntity:[NSEntityDescription entityForName:#"Place" inManagedObjectContext:context]];
[allTickets setIncludesPropertyValues:NO];
NSError * error = nil;
NSArray * ticks = [context executeFetchRequest:allTickets error:&error];
for (NSManagedObject * tick in ticks) {
NSArray *keys = [[[tick entity] attributesByName] allKeys];
NSDictionary *myDict = [tick dictionaryWithValuesForKeys:keys];
NSString *theDate = [myDict objectForKey:#"date"];
NSString *theName = [myDict objectForKey:#"name"];
NSString *theNumber = [myDict objectForKey:#"number"];
NSString * finalExport = [NSString stringWithFormat:#"%#%#%#", theDate, theName, theNumber];
NSLog(#"%#",finalExport);
the NSLog result print out all the entries in CoreData correctly, running each request one after the other.
My problem is that when i want to create a txt with the finalExport NSString, i only have the first request in the file.
For exemple i got an NSLog with :
01.01.2015 MYNAME 34555445
02.01.2015 MYNAME 34523445
03.01.2015 MYNAME 34115445
04.01.2015 MYNAME 34552345
But in the text file i only got
01.01.2015 MYNAME 34555445
So how can i have a text file with all the NSLog Results
Thanks in advance for your help ;)
EDIT ++++++++++++++
Here is the rest of the code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error;
BOOL succeed = [finalExport writeToFile:[documentsDirectory stringByAppendingPathComponent:#"Number.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
NSLog(#"NOT WORKING");
}
You need to make sure you write an array of entries to the file, not just one entry.

no visible #interface for 'UIImagePickerController

So my code says
no visible #interface for UIImagePicker Controller
I am using a Tab View Controller
My code for my FirstViewController.m is
#import "FirstViewController.h"
#interface FirstViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *bailey;
UIImagePickerController *baileys;
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction)takePhoto;
- (IBAction)chooseExisting;
#end
#implementation FirstViewController
- (IBAction)takePhoto {
bailey = [[UIImagePickerController alloc]init];
bailey.delegate = self;
[bailey setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:bailey animated:YES completion:NULL];
}
- (IBAction)chooseExisting {
baileys = [[UIImagePickerController alloc] init];
baileys.delegate = self;
[baileys setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:baileys animated:YES completion:NULL];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)bailey {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)ShareFB {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[slComposeViewController addImage:[UIImage imageNamed:#"image"]];
[slComposeViewController addURL:[NSURL URLWithString:#"http://www.agfg.com.au"]];
[self presentViewController:slComposeViewController animated:YES completion:NULL];
//I borrowed these lines of code from http://www.bit.ly/174eqjy
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingString:#"upload.png"];
NSString *upLoad = [documentsDirectory stringByAppendingString:#"upload.png"];
NSData *myData = [[NSData alloc]initWithContentsOfFile:appFile];
//Here is the line that fails
[bailey addAttachmentData:myData mimeType:#"image/png" fileName:#"upload"];
//Up to here are the borrowed code lines.
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Facebook Account Detected" message:#"There are no Facebook Accounts Detected. You can configure them in Settings." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
}}
- (void)viewDidLoad
{
[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
And my code for my FirstViewController.h is
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#interface FirstViewController : UIViewController {SLComposeViewController *slComposeViewController;
UIImage *upLoad;}
- (IBAction)ShareFB;
#end
My app is designed to Take a photo and display the photo (and it does that) and then save that image to the local documents folder on the app (which I got from another post) and then specify that image to upload to Facebook (which I have)
All that works except the saving to a local documents.
If you need to store file in documents directory, use like this,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Images"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *imageFilePath = [NSString stringWithFormat:#"%#/%#",dataPath,#"upload.png"];
UIImage *image = [UIImage imageNamed:#"image"]; //Here place your image
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageData writeToFile:imageFilePath atomically:YES];
If you need to attach image in facebook, use this statement,
[slComposeViewController
addAttachmentData:UIImagePNGRepresentation(image, 1) mimeType:#"image/png" fileName:#"upload.png"];
With the help of Karthika, and his facebook upload code, I was typing it in when I realised that I did not need to implement local documents saving.
Facebook let me add the image in without saving it.
Thanks though Karthika, I could not have done it without you.

saving an image to documents directory - not working - only creating a zero byte file

I am trying to make a simple app to take a picture and save the file to both a UIImageview and to the documents folder so it can be recalled at a later time as the UIImageview. To get visibility into if the app is actually making a file, I have turned on Application supports iTunes File sharing within the .plist file.
Problem is the file generated is zero bytes. I have tried both PNG and JPG format.
- (IBAction)picImage:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
//check to see if the device has camera capability
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
else
{
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//set the UIImageView to the selected image
playerImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
//obtaining saving path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"player.png"];
UIImage *editedImage = [UIImage imageWithContentsOfFile:imagePath];
NSData *imageData = UIImagePNGRepresentation(editedImage);
//NSData *imageData = UIImageJPEGRepresentation(editedImage,1.0);
// This actually creates the image at the file path specified, with the image's NSData.
[[NSFileManager defaultManager] createFileAtPath:imagePath contents:imageData attributes:nil];
//dismiss the imagepicker view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
Try this code and let me know is it working or not..!!!!
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strimagename;
strimagename=[NSString stringWithFormat:#"Test.jpg"];
NSString *thumbFilePath = [documentsDirectory stringByAppendingPathComponent:strimagename];
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *thumbData = UIImageJPEGRepresentation(image, 1);
[thumbData writeToFile:thumbFilePath atomically:YES];
[imgPicker dismissModalViewControllerAnimated:YES];
This code will save image in documentory folder..
Happy Coding..!!!!!!

How to save and load a picture in Xcode

Check my app if you don't really understand ( Quick Notes!) But here it goes. My app is a notes app so it allows the user to select from few different kinds of note colors and designs below. When the user selects one, it changes the note above to what ever they set it to. So i need a button that will save the picture they selected, and when the leave the view and come back they can click the load button and the same image they selected will appear. I am using Xcode 4.3.
NSImageView is what your looking for.
This contains info on saving the file (look at the answer with code): Implement drag from NSImageView and save image to a file
The Code:
-(IBAction)saveImageButtonPushed:(id)sender
{
NSBitmapImageRep *rep;
NSData *data;
NSImage *image;
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
[self unlockFocus];
image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
[image addRepresentation:rep];
data = [rep representationUsingType: NSPNGFileType properties: nil];
//save as png but failed
[data writeToFile: #"asd.png" atomically: NO];
//save as pdf, succeeded but with flaw
data = [self dataWithPDFInsideRect:[self frame]];
[data writeToFile:#"asd.pdf" atomically:YES];
}
//......
#end
To load an image:
The Code:
NSImage loadedImage = [[NSImage alloc] initWithContentsOfFile: NSString* filePath]
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSDate *date = [[NSDate date] dateByAddingTimeInterval:1];
profile_img = [NSString stringWithFormat:#"%#.png",[dateFormatter stringFromDate:date]];
[profile_img retain];
NSLog(#"formattedDateString: %#",profile_img);
NSData *imageToUpload = UIImagePNGRepresentation(Img_View.image);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:ServerPath]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"Upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:profile_img mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject)
{
NSString *response = [operation2 responseString];
NSLog(#"response: [%#]",response);
NSString *post = [NSString stringWithFormat:#"Images=%#",profile_img];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [post length]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Gallery.php",ServerPath]];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"POST"];
NSLog(#"%#", post);
[request1 setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request1 setHTTPBody:postData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSString *responseString = [[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding] autorelease];
responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",responseString);
if([responseString isEqualToString:#"Entered data successfully"])
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Image Share" message:#"Image Share SuccessFully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[Alert show];
[Alert release];
}
else
{
}
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
NSLog(#"error: %#", [operation2 error]);
}];
[operation2 start];

How to write Boolean to a plist file

I'm trying to write Boolean to a plist file. My code is:
NSString *filePath = [self dataFilePath];
if (filePath)
{
if (check)
{
NSLog(#"Clear");
[item setObject:[NSNumber numberWithBool:NO] forKey:#"check"];
[item writeToFile:filePath atomically: YES];
}else{
NSLog(#"Green");
[item setObject:[NSNumber numberWithBool:YES] forKey:#"check"];
[item writeToFile:filePath atomically: YES];
}
NSLog([[NSString alloc] initWithContentsOfFile:filePath]);
}else{
NSLog(#"write file was not found");
}
My filePath is:
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"CheckMark.plist"];
}
I load my array with:
- (void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
NSLog(#"%#", filePath);
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:#"CheckMark" ofType:#"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:myPathInfo toPath:filePath error:NULL];
}
// load our data from a plist file inside our app bundle
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog([[NSString alloc] initWithContentsOfFile:filePath]);
NSLog(#"%#", filePath);
NSLog(#"read dataArray");
Every thing works fine, except when I look at the plist file, nothing changes.
I'm writing the plist file to my Documents directory.
Thanks for any help you can give me.
Remember that you need to be using an NSMutableDictionary to be able to set values.

Resources