Creating and attaching a .txt file to email in Xcode [closed] - ios

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 8 years ago.
Improve this question
I want to make an iOS app that makes/creates a text file (.txt) then sends it as an email.
The issue i am having is the data to be encrypted pops up with the error "use of undeclared identifier"
[mailController addAttachmentData:dataToBeEncrypted mimeType:#"text/plain"
Here is my .m file
//
// FileIoViewController.m
// FileIo
//
// Created by Flare gun on 6/24/14.
// Copyright (c) 2014 Flaregunapplications. All rights reserved.
//
#import "FileIoViewController.h"
#interface FileIoViewController ()
#end
#implementation FileIoViewController
- (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.
}
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
mailController.mailComposeDelegate =self;
[mailController setSubject:#"Records"];
[mailController setMessageBody:#"" isHTML:YES];
[mailController addAttachmentData:dataToBeEncrypted mimeType:#"text/plain" fileName:#"Records.txt"];
[self presentModalViewController:mailController animated:YES];
[mailController release];
} else {
//Pop up a notification
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Could not send email. Verify Internet conneciton and try again." delegate:nil cancelButtonTitle:#"Done" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
#end

To declare dataToBeEncrypted use something like:
NSData *dataToBeEncrypted = [NSData dataWithContentsOfFile:filename];

Related

ZBar SDK slowing down in IOS7

I am trying to implement some qr code reader using ZBar.
After a while I did manage to do reading, but after several readings the app tends to get slower and slower (until practically unresponsive).
This SDK is compatible with iOS7 ?
Frameworks : libiconv.dylib,libinfo.dylib, QuartzCore, CoreVideo,CoreMedia,AVFoundation,CoreGraphics,UIKit,XCTest
- (IBAction)scan:(id)sender {
//initialize the reader and provide some config instructions
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
[reader.scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 1];
reader.cameraFlashMode=UIImagePickerControllerCameraFlashModeOff;
reader.readerView.zoom = 1.0; // define camera zoom property
//show the scanning/camera mode
[self presentModalViewController:reader animated:YES];
// Do any additional setup after loading the view from its nib.
}
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info {
//this contains your result from the scan
id results = [info objectForKey: ZBarReaderControllerResults];
//create a symbol object to attach the response data to
ZBarSymbol *symbol = nil;
//add the symbol properties from the result
//so you can access it
for(symbol in results){
//symbol.data holds the value
NSString *upcString = symbol.data;
//print to the console
NSLog(#"the value of the scanned UPC is: %#",upcString);
NSMutableString *message = [[NSMutableString alloc]
initWithString: #"Scanned Barcode: "];
[message appendString:[NSString stringWithFormat:#"%# ",
upcString]];
//Create UIAlertView alert
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Product Barcode" message: message delegate:self
cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
self.viewResult.text = upcString;
[alert show];
//After some time
[alert dismissWithClickedButtonIndex:0 animated:TRUE];
//make the reader view go away
[reader dismissModalViewControllerAnimated: YES];
}
}
EDIT : After 4 or 5 readings, this is the memory and CPU consumption -> http://diogomend.me/images/capt.png. Christ :D
Well, after checking this issue Memory related issue of ZBarReaderViewController in iOS 7, I did manage to solve the problem.
The lines I've added are the following:
(in my viewcontroller.h)
#property (strong,nonatomic) ZBarReaderViewController *reader;
(in my viewcontroller.m)
if(self.reader)
{
[self.reader.readerView stop];
for(UIView *subViews in self.reader.view.subviews)
[subViews removeFromSuperview];
[self.reader.view removeFromSuperview];
self.reader.view = nil;
}
_reader = [ZBarReaderViewController new];

iOS contact form issue [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi i am new to using the iOS SDK and i am trying to make a basic contact form with a name, address, email etc... here's what i have done so far.
'- (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.
}
- (IBAction)emailButton:(id)sender {
MFMailComposeViewController *mailContoller = [[MFMailComposeViewController alloc]init];
[mailContoller setMailComposeDelegate:self];
NSString *email = #"******#gmail.com";
NSString *email1 = #"*******#hotmail.co.uk";
NSArray *emailArray = [[NSArray alloc]initWithObjects:email, email1, nil];
NSString *message = [[self myTextView]text];
[mailContoller setMessageBody:message isHTML:NO];
[mailContoller setToRecipients:emailArray];
[mailContoller setSubject:#"IT WORKS!"];
[self presentViewController:mailContoller animated:YES completion:nil];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self myTextView] resignFirstResponder];
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
the problem i am having is that i do not know how to make multiple text fields that will be sent together via email.
thanks and any help would be greatly appreciated.
Simply concatenate the strings from the text fields.
NSString *message = [NSString stringWithFormat:#"%#\n%#\n%#",
textField1.text, textField2.text, textField3.text];

Send Contact Form Fields in Email

I have a contact form made of text fields (5 fields) that I would like to send via email to a single email address. How do I do this in xCode?
For anyone stumbling across this question, you can use this drop-in iOS contact form.
This fit my needs well, it uses a PHP component to actually send the email. (an example script is included in the sample project.
I posted it to Github here:
https://github.com/mikecheckDev/MDContactForm
The linked post has a similar answer, but I'm adding my code since it checks for canSendMail already. I also left in a bunch of commented code that makes it easy to add other stuff to the email.
Note that this is substantially easier if you are only targeting iOS 5.
I have a free app, QCount, that uses this code. Indeed, I hope I stripped everything custom from my copy-and-paste :-) http://itunes.apple.com/ng/app/qcount/id480084223?mt=8
Enjoy,
Damien
In your .h:
#import <MessageUI/MessageUI.h>
Methods in your .m:
- (void)emailLabelPressed { // or whatever invokes your email
// Create a mail message in the user's preferred mail client
// by opening a mailto URL. The extended mailto URL format
// is documented by RFC 2368 and is supported by Mail.app
// and other modern mail clients.
//
// This routine's prototype makes it easy to connect it as
// the action of a user interface object in Interface Builder.
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
if (mailClass != nil)
{
// We must always check whether the current device is configured for sending emails
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}
else
{
[self launchMailAppOnDevice];
}
}
-(void)displayComposerSheet {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Your Form Subject"];
// Take screenshot and attach (optional, obv.)
UIImage *aScreenshot = [self screenshot];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(aScreenshot)];
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"screenshot"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"first#example.com", nil];
// NSArray *ccRecipients = [[NSArray alloc] init];
// NSArray *bccRecipients = [[NSArray alloc] init];
// NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
// NSArray *bccRecipients = [NSArray arrayWithObjects:#"fourth#example.com", nil];
[picker setToRecipients:toRecipients];
// [picker setCcRecipients:ccRecipients];
// [picker setBccRecipients:bccRecipients];
// Attach an image to the email.
/* NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano"
ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/png"
fileName:#"ipodnano"];
*/
// Fill out the email body text.
// NSString *emailBody = #"Use this for fixed content.";
NSMutableString *emailBody = [[NSMutableString alloc] init];
[emailBody setString: #"Feedback"];
// programmatically add your 5 fields of content here.
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]) {
[self presentViewController:picker animated:YES completion:nil];
} else {
[self presentModalViewController:picker animated:YES];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
}
-(void)launchMailAppOnDevice {
NSString *recipients = #"mailto:first#example.com?cc=second#example.com,third#example.com&subject=Hello from California!";
NSString *body = #"&body=Feedback";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

File Name NSString adds unnecessary %20 in space

SOLVED (Thanks Regexident)
I have an app that passes the file path of a PDF to a custom -(id)init init method. It is added to the table and when it is selected, it calls the else statement for a non existent file:
- (void) gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index {
NSLog (#"Selected theArgument=%d\n", index);
UIViewController *viewController = [[[UIViewController alloc]init]autorelease];
{
//if file is built-in, read from the bundle
if (index <= 3)
{
// first section is our build-in documents
NSString *fileURLs = [_documentIconsURLs objectAtIndex:index];
NSLog(#"file url -%#", fileURLs);
viewController = [[[xSheetMusicViewController alloc]initWithContentURL:fileURLs]autorelease];
}
//if file is external, read from URL
else
{
// second section is the contents of the Documents folder
NSString *fileURL = [_documentIconsURLs objectAtIndex:index];
NSLog(#"file url -%#", fileURL);
NSString *path;
NSString *documentsDirectoryPath = [self applicationDocumentsDirectory];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileURL];
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectoryPath])
{
viewController = [[[xSheetMusicViewController alloc]initWithDocumentURL:fileURL]autorelease];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure!" message:#"The Selected File Does Not Exist"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
return;
}
}
[self.navigationController setNavigationBarHidden:YES animated:NO];
[UIView beginAnimations:#"animation" context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:YES];
[self.navigationController pushViewController:viewController animated:NO];
[UIView commitAnimations];
}
}
So whenever I have a document with no space in it's name, it pushes and inits. But when the file name has a space in it, it says it does not exist. And when I remove the if-else method, it init's, but crashes because the file doesn't exist. I've tried to replace the %20 in the file path with a regular space, but the method continues to call the else part.
So, is the file path not standardized and readable, or is my else method wrong?
As your path appears to be a percentage escaped path string I'd try this:
[fileURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
And I'd rename fileURL to fileURLString to make clear that it's an NSString containing a URL path, not an actual NSURL (which your variable name would falsely imply).
But I'd check the code that populates _documentIconsURLs, as it's probabaly the origin of your problem.

Unable to send email using MFMailComposeViewController in simulator

I am new to ios app development, Below is the code I used to send an email.
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"My Subject"];
[controller setMessageBody:#"Hello there." isHTML:NO];
[self presentModalViewController:controller animated:YES];
[controller release];
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error {
if (result == MFMailComposeResultSent) {
NSLog(#"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
Unfortunately delegate methods are never triggered , Can any one please suggest how can i check my email via simulator?
You CANNOT send mails through Simulator.
Instead you can install the application in device and try from there.
Simulator just displays the composer but wont allow you to send mails. Sent Successfully is just the acknowledgment that your code is fine and there is no issue that terminates it while sending.
As far as i know, you cannot send mail from Simulator.. The MFMailComposeViewController uses the mailbox configured in iPhone's Mail app to send the mail. The simulator does not have the Mail app.
You can able to send mail using the Gmail connectivity you can send mail to user for that you need to insert the some amount of code and setting in your code following code which use for sending a mail.
- (IBAction)sendMessageInBack:(id)anObject{
NSLog(#"Start Sending");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"sample.pdf"];
NSData *dataObj = [NSData dataWithContentsOfFile:writableDBPath];
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = #"Your mail id";
testMsg.toEmail = #"sender mail ids";
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"Uour mail id";
testMsg.pass = #"your pass";
testMsg.subject = #"Test application ";
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
// testMsg.validateSSLChain = NO;
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
#"Some text to include in body",kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
-(void)messageSent:(SKPSMTPMessage *)message{
[message release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
[message release];
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
And following files copy into your project.
For downloading a sample code here.

Resources