Sending email in iPhone - iphone

In my application I have to send feedback to the client's email.
Here is my code,
-(void) send:(id) sender {
[self sendEmailTo:[txtTo text] withSubject:[txtSubject text] withBody:[txtBody text]];
}
-(void) sendEmailTo:(NSString *)to withSubject:(NSString *) subject withBody:(NSString*)body {
NSString *mailString = [NSString stringWithFormat:#"mailto:?to=%#&subject=%#body=%#",
[to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
}
But this does not work. Is it require any type of SMTP setting or something else?
I tried apple's MailComposer sample but it also does not work.
Please help me.

I have posted this here, but for the sake of not clicking again here it is:
You need to include the MessageUI.framework into your project, and inside your header file you need to set the delegate:
#import <MessageUI/MessageUI.h>
#interface RootViewController : UIViewController <MFMailComposeViewControllerDelegate> {
MFMailComposeViewController *email;
}
#property (nonatomic, retain) MFMailComposeViewController *email;
Once you do that, you have a few delegate methods inside your implementation file you need to include (You should check to see the result, but I am trying to keep as little code as needed):
#synthesize email;
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[email dismissModalViewControllerAnimated:YES];
}
Wherever you want to use this, you need to initialize and set it up like this:
email = [[MFMailComposeViewController alloc] init];
email.mailComposeDelegate = self;
// Subject
[email setSubject:#"Testing"];
// Optional Attachments
NSData *artwork = UIImagePNGRepresentation([UIImage imageNamed:#"albumart.png"]);
[email addAttachmentData:artwork mimeType:#"image/png" fileName:#"albumart.png"];
// Body
[email setMessageBody:#"This is the body"];
// Present it
[self presentModalViewController:email animated:YES];

Try to use different format:
NSString *mailString = [NSString stringWithFormat:#"mailto:%#?subject=%#&body=%#",
[to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

Related

Mail Composition Interface Doesn't Appear?

I'm trying to replicates Apple "Sending a Mail Message" code, but the email composition interface doen't appear.. just a blank screen. I think I did this right. Didn't do anything with the storyboard since there aren't any actions or outlets. Didn't change either of the delegate .h or .m files. Below is the code. Very new to coding. What have I missed?
.h file
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#interface ViewController : UIViewController <MFMailComposeViewControllerDelegate>
#end
.m file
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello from New Zealand!"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"jfellows123#gmail.com",
nil];
NSArray *ccRecipients = [NSArray arrayWithObjects:#"jfellows123#gmail.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObjects:#"jfellows123#gmail.com",
nil];
[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
NSString *path = [[NSBundle mainBundle] pathForResource:#"IMG_3639"
ofType:#"jpg"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/jpg"
fileName:#"IMG_3639"];
// Fill out the email body text.
NSString *emailBody = #"Beautiful New Zealand!";
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
// The mail compose view controller delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
If you don't mind . Where you are calling the -(void)displayComposerSheet method. ?
It doesn't get called right . If so Let me know your log . Use breakPoints .

Get the Query Of a UIWebView URL

Hey guys I'm trying to find a way to specifically grab the Query String out of the URL that my UIWebView currently has loaded up.
So for example:
www.google.com?page=235
I want to end up with a NSString with the text "page=235".
Or even better Page at a NSData Key of Title and 235 at a Key of ID.
Im basically trying to organise the Query String into useable data.
In my project I have a button:
[HTML appendString:#"<a href='didtap://goto?Page=56'>Post Comment</a>"];
That i access with checking the absolute URL to see if the button was fired.
Is there any way to profile the information the way i want to?
I create the demo what you want get which is describe further..
Following is the viewcontroller.h file code
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
NSURL *Url;
}
#property(nonatomic,retain)IBOutlet UIWebView *webVctr;
#end
This may helping to solve your problem
Thanks
Following is the viewcontroller.m file code
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize webVctr = _webVctr;
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(#"%#",request);
Url = [request URL];
// if ([[UrlParts objectAtIndex:(1)] isEqualToString:#"NeverGonnaFindMe"]) {
// CONVERT TO STRING AN CLEAN
NSString *urlResources = [Url resourceSpecifier];
urlResources = [urlResources stringByReplacingOccurrencesOfString:#"?" withString:#"/"];
// SEPORATE OUT THE URL ON THE /
NSArray *urlResourcesArray = [urlResources componentsSeparatedByString:#"/"];
// THE LAST OBJECT IN THE ARRAY
NSString *urlParamaters = [urlResourcesArray objectAtIndex:([urlResourcesArray count]-1)];
// SEPORATE OUT THE URL ON THE &
NSArray *urlParamatersArray = [urlParamaters componentsSeparatedByString:#"&"];
if([urlParamatersArray count] == 1) {
NSString *keyValue = [urlParamatersArray objectAtIndex:(0)];
NSArray *keyValueArray = [keyValue componentsSeparatedByString:#"="];
if([[keyValueArray objectAtIndex:(0)] isEqualToString:#"page"]) {
NSLog(#"%#",[keyValueArray objectAtIndex:1]);
}
[self dismissModalViewControllerAnimated:YES];
return NO;
}
return YES;
}
// ACTIVITY INDICATOR
- (void)webViewDidStartLoad:(UIWebView *)webView{
/// [_activityIndicator startAnimating];
NSLog(#"Resting to server");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
// [_activityIndicator stopAnimating];
NSLog(#"Finish request server");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(#"Error");
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *fullAuthUrlString =[[NSString alloc] initWithFormat:#"www.google.com?page=235"];
NSURL *authUrl = [NSURL URLWithString:fullAuthUrlString];
NSURLRequest *myRequest = [[NSURLRequest alloc] initWithURL:authUrl];
[self.webVctr loadRequest:myRequest];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
To get the query string, get the query string of a NSURL object.
NSURL *url = …;
NSString *queryString = url.query;
For more information, see Accessing the Parts of the URL in the NSURL class documentation.

NSURLConnection and JSON Data

I am stuck with something crazy. I used ASIHTTPRequest to receive my data from a web service and everything worked fine. I switched to using a NSURLConnection and I am receiving the same data and parsing it the same way but my code won't recognize the data with the NSURLConnection.
Here is the data I am receiving (from NSLog)
Did receive data: {"d":"[{\"id\":1.0,\"Category\":1,\"hPlan\":0.0,\"Tip\":\"It takes 3500
calories to gain a pound. If you want to lose a pound per week, reduce your calorie
intake by 250 calories and incorporate daily physical activity that will burn 250
calories.\",\"TipDate\":\"2012-05-12T00:00:00\",\"TimeStamp\":\"AAAAAAAAB9I=\"}]"}
2012-06-06 09:42:11.809 StaticTable[27488:f803] Jsson Array: 0
2012-06-06 09:42:11.809 StaticTable[27488:f803] Jsson Array: (null)
Code:
#import "UYLFirstViewController.h"
#import "MBProgressHUD.h"
#import "JSON.h"
#interface UYLFirstViewController ()
#end
#implementation UYLFirstViewController
#pragma mark -
#pragma mark === UIViewController ===
#pragma mark -
#synthesize MessageField;
#synthesize jsonArray = _jsonArray;
#synthesize TipLabelField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Tickle!", #"Tickle!");
self.tabBarItem.image = [UIImage imageNamed:#"heart_plus"];
[self GetTipOfDay];
}
return self;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
-(BOOL)GetTipOfDay{
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
NSString *dateString = [dateFormat stringFromDate:date];
NSString *yourOriginalString = #"Tip of the Day for ";
yourOriginalString = [yourOriginalString stringByAppendingString:dateString];
TipLabelField.text = yourOriginalString;
NSURL *url = [NSURL URLWithString:#"http://www.mysite.com/api/GetHealth.asmx/getTipOfDay"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection connectionWithRequest:request delegate:self];
// Clear text field
MessageField.text = #"";
// Start hud
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Gathering Tip of the Day...";
return TRUE;
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"Did receive data: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSDictionary *responseDict = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] JSONValue];
NSString *jsonResponse = [responseDict objectForKey:#"d"];
self.jsonArray = [jsonResponse JSONValue];
NSLog(#"Jsson Array: %d", [jsonArray count]);
NSLog(#"Jsson Array: %#", jsonArray);
NSEnumerator *myEnumerator;
myEnumerator = [jsonArray objectEnumerator];
int i;
i=0;
id myObject;
while (myObject = [myEnumerator nextObject])
{
NSDictionary *itemAtIndex = (NSDictionary *)[self.jsonArray objectAtIndex:i];
NSLog(#"Checking for games");
NSString *myCheck = [itemAtIndex objectForKey:#"FName"];
if ([myCheck length] != 0)
{
// NSLog(myCheck);
MessageField.text = myCheck;
}
}
}
- (void)viewDidUnload {
[self setMessageField:nil];
[self setTipLabelField:nil];
[super viewDidUnload];
}
#end
#import <UIKit/UIKit.h>
#interface UYLFirstViewController : UIViewController{
NSMutableArray *jsonArray;
}
#property (weak, nonatomic) IBOutlet UILabel *MessageField;
#property (weak, nonatomic) NSMutableArray *jsonArray;
#property (weak, nonatomic) IBOutlet UILabel *TipLabelField;
-(BOOL)GetTipOfDay;
#end
-didRecieveData can be called multiple times as the bytes and chunks come in. You should move your logic to -connectionDidFinishLoading. This will let you know when the connection is completely done and the data is ready to be parsed.
You're only implementing one of the NSURLConnectionDelegate methods. Try adding this
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//set up *receivedMutableString as instance variable in .h
if (!receivedMutableString) {
self.receivedMutableString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
} else {
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[receivedMutableString appendString:dataString];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//Now receivedMutableString contains all json data
...continue with your code
}
NSURLConnection is a bit of overkill if you're just doing a simple GET request (and you're developing for an iOS version that supports blocks). You can do this in a dispatch_async block:
- (void) getData
{
dispatch_async(<some_queue>, ^{
NSError * error = nil;
NSString * response = [NSString stringWithContentsOfURL: stringWithContentsOfURL: requestUrl error: &error];
// process JSON
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI on main thread
}
});
}
As you can see from my example code, you can also perform your JSON processing on the background queue (provided the method you're calling is thread safe). Just pass back to the main queue to update the UI.
Seems like the issue had nothing to do with fetching from the webservice. I had to define my array as __strong. Thanks for all the help. I did get some good ideas on how to do things better.

Mailbox programming in iphone?

I want saved email addresses of different users, and I want to open mailBox's new mail when I click the email, same as phonebook email in iphone,
what should I to do ???
You should use the MFMailComposeViewController class, and the implement MFMailComposeViewControllerDelegate protocol,
First to send a message:
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];
Once you sent you will get delegate callback in mailComposeController :
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(#"It's gone!");
}
[self dismissModalViewControllerAnimated:YES];
}
Create new message within Mail:
NSString *subject = #"The subject";
NSString *body = #"The message";
NSString *address = #"mail#address.com";
NSString *cc = #"mail#address.com";
NSString *path = [NSString stringWithFormat:#"mailto:%#?cc=%#&subject=%#&body=%#", address, cc, subject, body];
NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];

Email app from another app

I want to start an email app from app on button pressed. But when I pressed the button nothing is happening !!!
code :
- (IBAction) startMail
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"mailto:emailAdress?subject=testMail&body=its test mail."]];
}
any thing wrong in code ? Also button is properly set in IB.
Thanks..
If you want to compose an EMail inside your app, you should have a look at the MFMailComposeViewController reference to do so instead of calling a mailto: URL scheme.
Using the mailto URL won't work in the simulator as mail.app isn't installed on the simulator. It does work on device though.
You can use "MFMailComposeViewController" to send mail from your application.
Sample code-
MFMailComposeViewController *picker;
picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
NSString *objSubject = [[NSString alloc] init];<br/>
NSString *emailBody = [[NSString alloc] init];
[picker setSubject:objSubject];
[picker setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker animated:YES];
You must use the following delegate to check the status of mail sent or not
**-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
}**
Enjoy
Try this:
NSString *mailString = [NSString stringWithFormat:#"mailto:?to=%#&subject=%#&body=%#",
[to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
Here to, subject and body are NSString variables
Check this out, it's a better solution than directing your user out of the app;
How can I send mail from an iPhone application
NSString *url = [NSString stringWithString: #"mailto:foo#example.com?cc=bar#example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];