Hi All,

Today I am going to talk about iOS Delagates.
This example shows how to write a common delegate for a mail composer in iOS.

First I am going to crate a seperate class for invoking the MailComposer Modal view controller.
The class is named “Common”.

So Create .m and .h files for Common.


#import <Foundation/Foundation.h>
#import <MessageUI/MessageUI.h>

@interface Common : NSObject{
    MFMailComposeViewController *mailComposer;

@property (nonatomic, weak) id <MFMailComposeViewControllerDelegate> delegate;

-(void)sendMail:(UIViewController *) cont : (NSString *) mailSubject : (NSString *) mailBody;

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate;


Now Go to Common.m and implement the methods.

#import "Common.h"

@implementation Common

@synthesize delegate;

-(void)sendMail:(UIViewController *) cont :(NSString *) mailSubject : (NSString *) mailBody{
    mailComposer = [[MFMailComposeViewController alloc]init];
    [mailComposer setSubject:mailSubject];
    mailComposer.mailComposeDelegate = delegate;
    [mailComposer setMessageBody:mailBody isHTML:NO];
    [cont presentViewController:mailComposer animated:YES completion:nil];

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate{
    if (delegate != aDelegate) {
        delegate = aDelegate;        


Now Go to ViewController.h

We don’t need any declarations inside this class, just need to add the delegate

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>

Now in the implementation class


#import "ViewController.h"
#import "Common.h"

@interface ViewController ()


@implementation ViewController

- (void)viewDidLoad

    Common *com = [Common new];
    [com setDelegate:self];   // Setting the Mail Composer delegate
    [com sendMail:self :@"Mail Subject" :@"Mail Body"];

#pragma mark - mail compose delegate
-(void)mailComposeController:(MFMailComposeViewController *)controller
         didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    if (result) {
        NSLog(@"Result : %d",result);
    if (error) {
        NSLog(@"Error : %@",error);
    [self dismissViewControllerAnimated:YES completion:nil];

Ok. Now our MailComposer Delegate is implemented. Go on and run the application.


Leave a Reply

Your email address will not be published. Required fields are marked *




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.