Pages

Subscribe:

Thursday, January 5, 2012

How to send In-app SMS through iOS application

/* This feature is available in iOS 4 or later */

Step 1:

Import the MessageUI Framework into your project and #import the header file into the “.h” file of your controller where you want to open the In-App SMS sheet.

Step 2:

You might already have a button handler IBAction where you want to send the SMS. If not create a Button on your XIB file and write IBActions for it.

Step 3:

The real code

-(IBAction) sendInAppSMS:(id) sender
{
MFMessageComposeViewController *controller =
[
[[MFMessageComposeViewController alloc] init] autorelease];

if
([MFMessageComposeViewController canSendText])
{
controller.body = @"Hello from Erfan";
controller.recipients = [NSArray arrayWithObjects:
@
"12345678", @"87654321", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}

The most important part here is the line [MFMessageComposeViewController canSendText].
When sending a in-app email, you can choose to ignore this (atleast as of now) because most of the devices would have upgraded to iPhone OS 3 and all those devices would have the ability to send in-app email. However, the same doesn’t apply to SMS. Remember that even if a device is running iPhone OS 4, if it’s an iPod touch, it will never be abel to send SMS within app.
In this case, You have to use an if condition to send the SMS. Practically speaking, you should enable/disable the button the user taps to send the sms based on this. You can add the code that does this in your viewDidLoad method.

Step 4:

Implement Delegate Callbacks.
In your header file, implement the callbacks, MFMessageComposeViewControllerDelegate and UINavigationControllerDelegate. If you don’t you will get a warning at the line,

 controller.delegate = self;

You have to handle a callback method of MFMessageComposeViewControllerDelegate so as to dismiss the modal view controller.

- (void)messageComposeViewController:
(
MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result
{

switch (result)
{
case MessageComposeResultCancelled:
NSLog(@"Cancelled");
break
;
case MessageComposeResultFailed:
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"MyApp" message:@"Unknown Error"
delegate:self cancelButtonTitle:@”OK”
otherButtonTitles: nil];
[alert show];
[alert release];
break;
case
MessageComposeResultSent:
break
;
default:
break;
}

[self dismissModalViewControllerAnimated:YES];
}
That’s it. Your app should now be able to send SMS using the new Message UI sheet. :-)

No comments:

Post a Comment