How to send an SMS at a specific time - iphone

i'm new to iphone application development.
i'm creating a application to send sms.
In my application i need to send sms on specified time.
I have a time picker to specify the time in UITextField.
-(void)sendInAppSMS
{
NSLog(#"SendMessage");
if([textFieldRounded.text isEqualToString:#""] || [textFieldRounded1.text isEqualToString:#""] || [textFieldRounded2.text isEqualToString:#""] || [textFieldRounded.text isEqualToString:#"(null)"] || [textFieldRounded1.text isEqualToString:#"(null)"] || [textFieldRounded1.text isEqualToString:#"(null)"] || [textFieldRounded.text isEqualToString:nil] || [textFieldRounded1.text isEqualToString:nil]|| [textFieldRounded2.text isEqualToString:nil])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"SMS" message:#"Please Enter All Fields!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
}
else
{
NSLog(#"Done");
NSDateFormatter *SentTime = [[NSDateFormatter alloc] init];
[SentTime setDateFormat:#"dd/MM/YYYY hh:mm aa"];
NSDate *now1 = [NSDate date];
NSString *Time1 = [SentTime stringFromDate:now1];
NSLog(#"Time is :%#",Time1);
NSString *Sentime=[NSString stringWithFormat:#"%#",textFieldRounded2.text];
if([Sentime isEqualToString:Time1])
{
NSLog(#"Time Matching... can send msg now");
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
if([MFMessageComposeViewController canSendText])
{
NSString *Message = [NSString stringWithFormat:#"%#, %#",textFieldRounded1.text,textFieldRounded2.text];
NSLog(#"Message is %#", Message);
controller.body = Message;
controller.recipients = [NSArray arrayWithObjects:#"+919999999999" , nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
else
{
NSLog(#"Send Message when time reach at %#",textFieldRounded2.text);
//Here What code i should write
}
}
}
if the time is equal to current time then send the sms nowitself (no need to store the messsage anywhere).
Other wise i need to send that sms , when current time becomes as that specified time. Until the time reach how to keep(store) the message and send on the time.
Regards,
Rajendran.B

You can't send SMS using timer in iOS, Apple does not allow this functionality.
see this

In terms of user experience, your code is very unlikely to allow the user to send a message unless the current time matches the exact minute of the specified time. It would make more sense to check to see if the time is after or within a certain range of the specified time. Also of note, it would be easier to make these comparisons if you weren't comparing string literals. (use NSDate and associated convenience methods to make these comparisons)
In terms of sending a message at a certain time, this will likely require a server component in which you register the message to be sent and the time it should be sent, and then at specified intervals, process messages that are in the message send queue.

As has been pointed out in the other answers, it's not possible to "save" the message that the user has composed in the MFMessageComposeViewController to send at a later time (nor are there any other means to do so).
Your options are:
Collect the details for the SMS ahead of time, but then at the correct time prompt the user. You could use a UILocalNotification for this if the app might be closed. You can open a message with the right details prefilled using setTitle:, setBody:, and setRecipients: on the MFMessageComposeViewController instance, so the user will just have to hit send.
Send the message details back to a server, and send the SMS at the right time using some SMS system such as the Twilio api. This will add significant complexity, and the SMS wouldn't come from the user's phone number.

Related

Sending SMS to dynamic Telephone number

I have an app which sends an sms and then calls a dynamic telephone number, here is the code:
#pragma mark - PictureListMainTableCellDelegate methods
-(void)pictureListMainTableCell:(PictureListMainTableCell *)cell wantsToCallNumber:(NSString *)number
{
MFMessageComposeViewController *messageComposer =
[[MFMessageComposeViewController alloc] init];
NSString *message = #"Your Message here";
[messageComposer setBody:message];
messageComposer.recipients = [NSArray arrayWithObjects:#"0003233", nil];
messageComposer.messageComposeDelegate = self;
[self presentViewController:messageComposer animated:YES completion:nil];
NSLog(#"Texting telephone number [%#]", messageComposer);
NSString *urlString = [NSString stringWithFormat:#"tel://%#", number];
NSLog(#"calling telephone number [%#]", number);
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
NSLog(#"%#", [self deviceLocation]);
}
the telephone call works but not the sms, can anyone help?
First check if your device can send SMS messages by:
if ( [MFMessageComposeViewController canSendText] ) {
// build your text message like you posted
}
else {
// handle appropriately
// no point in trying to display the compose view controller
}
Whether this solves your specific problem, I am not sure, since I am just following Apple's docs for this.
just replace this line in your method and you'll be able to send dynamic messages
messageComposer.recipients = [NSArray arrayWithObjects:number,nil];
and you can send emails and messages automatically without pressing send button but in that case there is a chance of rejecting of your app from the apple app store as it is not under their legal process so they'll reject your application.
and you should check condition for
if([MFMessageComposeViewController canSendText])
otherwise in iPad and iPod your application might meet crash.

XMPPFramework message not sent

I receive messages from a Google Talk account, they are shown in the Table View in the Ios emulator, but when i send it, it is not shown in the Google Talk client (in another computer). This is the code:
-(IBAction)sendchat:(id)sender
{
General *general = [General sharedManager];//It is a singleton class used to store some values that need to be accesible in the whole application.
NSXMLElement *body = [NSXMLElement elementWithName:#"body"];
text=[mensaje text];
NSLog(#"Texto en el body: %#", text);
[body setStringValue:text];
NSArray *dest=[general.firstfrom componentsSeparatedByString:#"/"];//in firstfrom is stored the account from wich we receive the first message. This app cannot start a conversation itself, must only answer
NSLog(#"Destination trimmed: %#", [dest objectAtIndex:0]);//Here, the destination account shows correctly (without the /xxxx stuff, just name#gmail.com)
XMPPMessage *mens=[[XMPPMessage alloc]init];
[mens addAttributeWithName:#"body" stringValue:text];
[mens addAttributeWithName:#"sender" stringValue:general.userlogin];
NSLog(#"text vale: %#", text);
NSXMLElement *messagetosend = [NSXMLElement elementWithName:#"message"];
[messagetosend addAttributeWithName:#"type" stringValue:#"chat"];
[messagetosend addAttributeWithName:#"to" stringValue:[dest objectAtIndex:0]];
[messagetosend addChild:body];
NSLog(#"We are sending to: %#", [dest objectAtIndex:0]);
[self.xmppStream sendElement:messagetosend];
[self xmppStream:xmppStream didReceiveMessage:mens];//manage the sent message as it was received, to show it in the Table View
self.mensaje.text=#"";
}
As I say, messages are received perfectly, but I cannot send. Ive seen plenty of examples of how to send, and they are like my code. If i debug sender it is shown ok (namesender#gmail.com), and the "to" attribute is ok too (namereceiver#gmail.com). The xmppStrem is set correctly (as far as i know):
xmppStream = [[XMPPStream alloc] init];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
In ViewDidLoad method.
Any help? Thank you.
---EDIT---
I forgot to say, both accounts know each others and in the Google Talk client, the presence is sent.
I found the answer. I had two classes receiving messages, because Class A must receive a message to trigger the pushing of the view of the class B (this app is unable to start a chat conversation by itself). So, i set two xmppStream, one for every class. I put an xmppStream in my General class, make both classes take that xmppStream, and it now sends messages.

How to send mail from iphone app without showing MFMailComposeViewController?

I want to send mail from my custom iPhone app. I have used MFMailComposeViewController to send mail from my iphone in my previous app. Now, i don't want to show the MFMailComposeViewController to the user, if they click Send Mail button the mail automatically send to the recipient mail address. How can i do this? Can you please help me on this? Thanks in advance.
I have used below code to show the MFMailComposeViewController,
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Details"];
[controller setMessageBody:#"Hi" isHTML:NO];
[controller setToRecipients:[NSArray arrayWithObjects:#"abcd.m#gmail.com", nil]];
[self presentModalViewController:controller animated:YES];
[controller release];
Sending emails programmatically, without user intervention, from an iphone application, cannot be implemented using any of the Apple frameworks. It could be possible in a jailbroken phone but then it would never see the inside of App Store.
If you want control of email sending, then a better way would be to set up a web service (at your server end) you can post to using an HTTP request. If you are posting to only one address this can work very well, although you may want to get the user to input their return mail address.
Otherwise only the standard dialog is available (this relies on using whatever account they've setup on the device).
The iOS SDK has made it really easy to send email using the built-in APIs. With a few line of codes, you can launch the same email interface as the stock Mail app that lets you compose an email. You can pop up mail composer form , write message and can send plain mail or file attached mail using MFMailComposeViewController class. For more info : Sending e-mail from your iOS App
But, in this section what i am going to explain is about sending emails without showing the mail composer sheet ie. sending emails in background. For this feature, we can not use iOS native MFMailComposer class because it does not allow us to send emails in background instead it pop ups the mail composer view from where user have to tap "send" button , so for this section i am going to use SKPSMTPMessage Library to send emails in background, however email account has to be hardcoded on this method.
Limitations :
sender/receiver email address has to be hardcoded or you have to grab it using some pop up form in your app where user inputs sender/receiver email address. In addition, sender account credentials has to be also hardcoded since there is no way we can grab it from device settings.
Method :
Import CFNetwork.framework to your project.
Include #import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h" // for Base64 encoding
Include to your ViewController
Download SKPSMTPMessage library from
https://github.com/jetseven/skpsmtpmessage
Drag and Drop "SMTPLibrary" folder you have downloaded to your project.
Before proceeding, let you know that i am using sender/receiver email address and sender password hardcoded in the code for this example.But, you may grab this credentials from user, allowing them to input in some sort of forms(using UIViews).
-(void) sendEmailInBackground {
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"sender#gmail.com"; //sender email address
emailMessage.toEmail = #"receiver#gmail.com"; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"sender#gmail.com"; //sender email address
emailMessage.pass = #"Passwxxxx"; //sender email password
emailMessage.subject =#"#"email subject header message";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = #"your email body message";
//for example : NSString *messageBody = [NSString stringWithFormat:#"Tour Name: %#\nName: %#\nEmail: %#\nContact No: %#\nAddress: %#\nNote: %#",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
// Now creating plain text email message
NSDictionary *plainMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey, messageBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
//in addition : Logic for attaching file with email message.
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"JPG"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx- unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,#"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
*/
[emailMessage send];
// sending email- will take little time to send so its better to use indicator with message showing sending...
}
Now, handling delegate methods :
// On success
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
// On Failure
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
Ok, thats all from the coding side. hope this tutorial may find useful for you guyz

How to send an email to a receipent in background in iOS5?

In an iPhone app,I want to send an email to a person who has forgotten about their passcode . I want to send the mail in background (cant use MFMailComposeViewController for this) and also the app must not be pushed to background . Is there a way to achieve this?
The best way of doing this is using SKPSMTPMessage. You can download it from here: https://github.com/jetseven/skpsmtpmessage This is a very easy solution that I have used before for using "Forgot Password" solutions in iOS apps. To implement simply drag the downloaded files into your application, #import the the "SKPSMTPMessage.h" into your class, and implement the following code:
.h
#import "SKPSMTPMessage.h"
#interface SomeView : UIViewController <SKPSMTPMessageDelegate> {
}
- (IBAction)forgotPassword;
.m
- (IBAction)forgotPassword {
SKPSMTPMessage *forgotPassword = [[SKPSMTPMessage alloc] init];
[forgotPassword setFromEmail:#"some-email#gmail.com"]; // Change to your email address
[forgotPassword setToEmail:#"user-email#gmail.com"]; // Load this, or have user enter this
[forgotPassword setRelayHost:#"smtp.gmail.com"];
[theMessage setRequiresAuth:YES]; // GMail requires this
[forgotPassword setLogin:#"some-email#gmail.com"]; // Same as the "setFromEmail:" email
[forgotPassword setPass:#"password"]; // Password for the Gmail account that you are sending from
[forgotPassword setSubject:#"Forgot Password: My App"]; // Change this to change the subject of the email
[forgotPassword setWantsSecure:YES]; // Gmail Requires this
[forgotPassword setDelegate:self]; // Required
NSString *newpassword = #"helloworld";
NSString *message = [NSString stringWithFormat:#"Your password has been successfully reset. Your new password: %#", newpassword];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain", kSKPSMTPPartContentTypeKey, message, kSKPSMTPPartMessageKey, #"8bit" , kSKPSMTPPartContentTransferEncodingKey, nil];
[forgotPassword setParts:[NSArray arrayWithObjects:plainPart, nil]];
[forgotPassword send];
}
Also be sure to include the following methods in the .m. You can change the contents of the UIAlertViews depending on what you want to display to the user.
- (void)messageSent:(SKPSMTPMessage *)message {
NSLog(#"Message Sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Password Reset" message:#"Check your email for your new password." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
NSLog(#"Message Failed With Error(s): %#", [error description]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was an error reseting your password. Please try again later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
You also need to do the following before this will work.
Your Target -> Get Info -> Build -> All Configurations -> Other Link Flags: "-ObjC"
If you need help with this, see http://developer.apple.com/qa/qa2006/qa1490.html
EDIT:
* CFNetwork.framework must also be added for this to work! *
Let me know if you have any more questions.
Thanks,
Jacob
You can't use MFMailComposeViewController to do this. No API will allow you to send emails or any kind of message on behalf of the user without he seeing it.
The only I see is to make a call to your server and the server send the email, something like this:
NSURLRequest requestWithURL:[NSURL urlWithString:#"http://server.com/send_passcode?to=email#lala.com"]];
You cannot send SMS/Email without user acceptance. But there are a lot of web-services in internet which can send SMS/Email. I guess some app uses those services or uses own.
You CAN send email in the background (without using the default MFMail Controller). BUT you still need the user to fill out whatever form (or content you want to email) and have them click "Send".
Here is my post on how to do it. It includes code and images.
Locking the Fields in MFMailComposeViewController
P.S. this works and Apple has approved over 10 of my apps that use this code/method.
In reference to the PostageApp comment below if you wanted to send emails without any hassle of setting up an SMTP client you can check out the PostageKit wrapper for using the PostageApp service. Let's you send emails with a couple lines of code reliably.
https://github.com/twg/PostageKit
May be you should implement PHP script that will send out email to user. In ios, you can use POST method in NSURLConnection to call PHP script. You can find many scripts on Google to send out email to user.
Download SKPSMTP Library and import
#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"
-(IBAction)btnRecoverClicked:(id)Sender;
Then implement the method for sending mail in background.
-(IBAction) btnRecoverClicked:(id)sender {
NSString *str=#"Your password is:";
NSString *strUserPassword=[NSString stringWithFormat:#"%# %#",str,struserPassword];
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"XXXXX"; //sender email address
emailMessage.toEmail = struserEmail; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"xxxxxxxx"; //sender email address
emailMessage.pass = #"XXXXXXX"; //sender email password
emailMessage.subject =#"Password Recovery";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = [NSString stringWithFormat:#"Your password is: %#",struserPassword]
;
//for example : NSString *messageBody = [NSString stringWithFormat:#"Tour Name: %#\nName: %#\nEmail: %#\nContact No: %#\nAddress: %#\nNote: %#",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
// Now creating plain text email message
NSDictionary *plainMsg = [NSDictionary
dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
messageBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
//in addition : Logic for attaching file with email message.
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"JPG"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-
unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,#"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
*/
[emailMessage send];
// sending email- will take little time to send so its better to use indicator with message showing sending...
}
To handle the success and fail use
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent to your mail." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
and
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
https://github.com/troyz/MailUtil
I have used library above to send mail in background, so it works.
pod "MailUtil", :git => 'https://github.com/troyz/MailUtil.git', :tag => '0.1.0'
Swift code is here:
import MailUtil
SendEmailOperation.setupConfig(withServer: "smtp.foo.com", withFrom: "foo#mailserver.com", withLogin: "foo#mailserver.com", withPassword: "*********")
let operation = SendEmailOperation(to: "foo#mailserver.com", subject: "Hello", body: "world", path: "/selected/path/for/your/file.pdf")
operation?.completionBlock = {
debugPrint("Mail sent!")
DispatchQueue.main.async {
//showMailSentPopup()
}
}
do {
try SendEmailOperation.sendEmail(operation)
} catch {
debugPrint("Mail could not sent or sending result could not handle - \(error)")
}

Iphone sms app issue

iam making an application where i have to send a same body sms to my contact list . I m using
Class messageClass = (NSClassFromString(#"MFMessageComposeViewController"));
if (messageClass != nil)
{
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
if ([appdelegate.NumberArray count] > 0) {
NSString *aa = [appdelegate.NumberArray objectAtIndex:0];
NSMutableArray *myArray = [aa componentsSeparatedByString:#","];
NSString *n = [myArray objectAtIndex:0];
NSString *m=[myArray objectAtIndex:1];
NSString *new = [appdelegate.globalmsg stringByReplacingOccurrencesOfString: #"forgot" withString:n];
controller.body = new;
controller.recipients= [NSArray arrayWithObject:m];
controller.messageComposeDelegate = self;
//if([appdelegate.NumberArray count] ==2 ){
[self presentModalViewController:controller animated:YES];
im taking out my contact one by one from my mutable array . the problem is that my program sending an sms one at a time, not to the complete list. and if i wanted to send sms to next person i have to click send button again. is there any way i can send sms to everyone without clicking that send button again again?
u can check this app .... http://itunes.apple.com/us/app/automatic-custom-sms/id409247779 in this app last page comes automatically and send everyone from your contact list. ??
Ok i fix it. i use a local variable an initialize it in view did load with value 0 and then in view did appear update it to 1 and make making present model view appear till my array finished.