Delegates in iOS – A Simple Example

By | October 27, 2014

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.

Common.h

#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;
 
@end

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;       
    }
}
 
@end

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>
{
     
}
@end

Now in the implementation class

ViewController.m

#import "ViewController.h"
#import "Common.h"
 
@interface ViewController ()
 
@end
 
@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 *