Friday 8 June 2012

Share Class : Email, SMS, Fb , twitter

======== Calling way  ======================= 
#import "ShareViewController.h"

ShareViewController *svc;

- (IBAction)ButtonSharePressed:(id)sender{
  
    svc = [ShareViewController new];
  
    [svc setStringMessage:@"this is a message"];
  
    [svc startShare:self];
  
}



======== ShareViewController.h =======================
//
//  ShareViewController.h
//  WhatzzApp
//
//  Created by Gaurav D. Sharma on 04/06/12.
//  Copyright (c) 2012 KIPL. All rights reserved.
//

// EMail SMS lib
#import <MessageUI/MFMailComposeViewController.h>
#import <MessageUI/MessageUI.h>

// Facebook Lib.
#import "Facebook.h"

// twitter lib : Twitter framework iOS 5
#import <Twitter/Twitter.h>

@interface ShareViewController : UIViewController<UIActionSheetDelegate, FBSessionDelegate, FBRequestDelegate, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate, UIAlertViewDelegate>
{
    // Facebook instance
    Facebook *facebook;

}
/**
 *  viewController of self
 * pass self as viewController
 * require to show action sheet on the viewcontroller
 */
@property (nonatomic, strong) id viewController;

@property (nonatomic, strong) NSString *stringSubject;

@property (nonatomic, strong) NSString *stringMessage;

/**
 * start action sheet and show the options
 * aViewController of self
 * pass self as aViewController
 * require to show action sheet on the viewcontroller
 */
- (void)startShare:(UIViewController*)aViewController;
/**
 * Email share button pressed
 * send email though iPhone
 */
- (void)buttonEmailSharePressed;
- (void)sendMail:(NSArray*)mailIDs andSubject:(NSString*)subject andBody:(NSString*)body;

/**
 * SMS share button pressed
 * send SMS though iPhone
 */
- (void)buttonSMSSharePressed;
- (void)sendSMS:(NSArray*)numbers withMessage:(NSString*)message;

/**
 * Facebook share button pressed
 * post detail on self facebook wall
 */
- (void)buttonFBSharePressed;

- (void)postOnFacebookWall:(NSString*)stringPost;

/**
 * twitter share button pressed
 * post detail on self twitter wall
 */
- (void)buttonTwitterSharePressed;
- (void)twitterPostSuccessfully;
- (void)twitterPostCancel;

@end

======== ShareViewController.m =======================
//
//  ShareViewController.m
//  WhatzzApp
//
//  Created by Gaurav D. Sharma on 04/06/12.
//  Copyright (c) 2012 KIPL. All rights reserved.
//
/* --- --- */

#import "ShareViewController.h"
#import "AppDelegate.h"

@implementation ShareViewController

@synthesize viewController;

@synthesize stringSubject;

@synthesize stringMessage;

#pragma mark - View lifecycle
- (void)startShare:(UIViewController*)aViewController{
   
    /* --- copy the viewController--- */
    viewController = (id) aViewController;
   
    /* --- posting Subject --- */
    stringSubject = @"Whatzz’app –  worth a look!";
   
    /* --- Make action sheet--- */
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Share With"
                                                       delegate:self
                                              cancelButtonTitle:@"Close"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"Email", @"SMS",@"Facebook",@"Twitter", nil];

  
    /* --- show action sheet on the tab bar --- */
    [sheet showFromTabBar:[AppDelegate sharedInstance].tabBarController.tabBar];
   
    /* --- show action sheet on the view controller --- */
//    [sheet showInView:aViewController.view];
}

#pragma actionsheetdelegate
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:{
            /* --- Email Share --- */
            [self buttonEmailSharePressed];
        }
            break;
           
        case 1:{
            /* --- SMS Share --- */
            [self buttonSMSSharePressed];
        }
            break;
           
        case 2:{
            /* --- Facebook Share --- */
            [self buttonFBSharePressed];
        }
            break;
           
        case 3:{
            /* --- Twittor Share --- */
            [self buttonTwitterSharePressed];
        }
            break;
    }
}

#pragma mark - Email Share
- (void)buttonEmailSharePressed{
    /* --- send email --- */
    [self sendMail:nil
        andSubject:stringSubject
           andBody:stringMessage];
}

- (void)sendMail:(NSArray*)mailIDs andSubject:(NSString*)subject andBody:(NSString*)body {
   
    // setup mail object
    MFMailComposeViewController * mailView = [[MFMailComposeViewController alloc] init];
   
    // set delegate
    [mailView setMailComposeDelegate:self]; 
   
    // set to arrays
    //[mailView setToRecipients:mailIDs];
   
    // set subject
    [mailView setSubject:subject];
   
    // set body of mail
    body=[NSString stringWithFormat:@"<div><p>%@</p></div>", body];
   
    [mailView setMessageBody:body isHTML:YES];
   
    // show the default mail of iPhone on present view
    [viewController presentModalViewController:mailView animated:YES];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error {
    switch (result)
    {
        case MFMailComposeResultFailed:
        case MFMailComposeResultCancelled:
        case MFMailComposeResultSaved:
           
            [[[UIAlertView alloc] initWithTitle:@"ERROR"
                                        message:@"Your message has not been posted"
                                       delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil, nil] show];
           
            break;
           
           
        case MFMailComposeResultSent:
           
            [[[UIAlertView alloc] initWithTitle:@"Successful!"
                                        message:@"Your message has been posted"
                                       delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil, nil] show];
           
            break;
           
    }
    // remove model from current view
    [viewController dismissModalViewControllerAnimated:YES];
}



#pragma mark - SMS Share
- (void)buttonSMSSharePressed{
    /* --- send sms --- */
    [self sendSMS:nil
      withMessage:[stringSubject  stringByAppendingFormat:@" %@",stringMessage]];
}

- (void)sendSMS:(NSArray*)numbers withMessage:(NSString*)message{
   
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
   
    if (messageClass != nil) {    
       
        // Check whether the current device is configured for sending SMS messages
        if ([messageClass canSendText]) {
           
            MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
           
            [picker setRecipients:numbers];
           
            [picker setBody:message];
           
            picker.messageComposeDelegate = self;
           
            [viewController presentModalViewController:picker animated:YES];
           
        }
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result {
   
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MessageComposeResultCancelled:
        case MessageComposeResultFailed:
           
            [[[UIAlertView alloc] initWithTitle:@"ERROR"
                                        message:@"Your message has not been posted"
                                       delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil, nil] show];
           
            break;
           
           
        case MessageComposeResultSent:
           
            [[[UIAlertView alloc] initWithTitle:@"Successful!"
                                        message:@"Your message has been posted"
                                       delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil, nil] show];
           
            break;
    }
   
    [viewController dismissModalViewControllerAnimated:YES];
}


#pragma mark - Facebook Share
- (void)buttonFBSharePressed{
    /**
     * Initialize permissions  NSArray
     "installed": 1,
     "read_stream": 1,
     "user_birthday": 1,
     "user_religion_politics": 1,
     "user_relationships": 1,
     "user_relationship_details": 1,
     "user_hometown": 1,
     "user_location": 1,
     "user_likes": 1,
     "user_activities": 1,
     "user_interests": 1,
     "user_education_history": 1,
     "user_work_history": 1,
     "user_online_presence": 1,
     "user_website": 1,
     "user_groups": 1,
     "user_events": 1,
     "user_photos": 1,
     "user_videos": 1,
     "user_photo_video_tags": 1,
     "user_notes": 1,
     "user_about_me": 1,
     "user_status": 1,
     "friends_birthday": 1,
     "friends_religion_politics": 1,
     "friends_relationships": 1,
     "friends_relationship_details": 1,
     "friends_hometown": 1,
     "friends_location": 1,
     "friends_likes": 1,
     "friends_activities": 1,
     "friends_interests": 1,
     "friends_education_history": 1,
     "friends_work_history": 1,
     "friends_online_presence": 1,
     "friends_website": 1,
     "friends_groups": 1,
     "friends_events": 1,
     "friends_photos": 1,
     "friends_videos": 1,
     "friends_photo_video_tags": 1,
     "friends_notes": 1,
     "friends_about_me": 1,
     "friends_status": 1
     */
   
    NSArray *permissions = [[NSArray alloc] initWithObjects:
                            @"email",
                            @"publish_stream",
                            @"offline_access",
                            nil];
   
    // fb orignal instance
    facebook = (Facebook*)[AppDelegate sharedInstance].facebook;
   
    if (facebook && [facebook isSessionValid]) {
       
        [self postOnFacebookWall:stringMessage];
       
    } else {
       
        facebook = [[Facebook alloc] initWithAppId:kFBAppId andDelegate:self];
       
        // set AppDelegate facebook instance
        [AppDelegate sharedInstance].facebook = facebook;
       
        [facebook authorize:permissions];
    }

}
#pragma mark - My fb methods

- (void)postOnFacebookWall:(NSString*)stringPost{
    /* --- post on facebook wall --- */
    NSString *strPostOnWall = [stringSubject  stringByAppendingFormat:@" %@",stringMessage];
   
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   kFBAppId, @"api_key",
                                   strPostOnWall, @"message",
                                   @"http://www.konstantinfo.com/", @"link",
                                   @"http://www.konstantinfo.com/images/logo.png", @"picture",
                                   @"Konstant iPhone Testing", @"name",
                                   @"http://www.konstantinfo.com/", @"description",
                                   nil];
   
    [facebook requestWithGraphPath:@"me/feed"
                         andParams:params
                     andHttpMethod:@"POST"
                       andDelegate:self];
}


#pragma mark - FBSessionDelegate Methods
/**
 * Called when the user has logged in successfully.
 */
- (void)fbDidLogin{
    // set session of facebook
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
   
    // post on fb wall
    [self postOnFacebookWall:stringMessage];
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)fbDidNotLogin:(BOOL)cancelled{
   
}

/**
 * Called when the user logged out.
 */
- (void)fbDidLogout{
    // Remove saved authorization information if it exists
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"]) {
        [defaults removeObjectForKey:@"FBAccessTokenKey"];
        [defaults removeObjectForKey:@"FBExpirationDateKey"];
        [defaults removeObjectForKey:@"userLoginWithFacebook"];
        [defaults synchronize];
    }
}

/**
 * Called when the current session has expired. This might happen when:
 *  - the access token expired
 *  - the app has been disabled
 *  - the user revoked the app's permissions
 *  - the user changed his or her password
 */
- (void)fbSessionInvalidated{
    NSLog(@"fbSessionInvalidated");
}



#pragma mark - FBRequestDelegate Methods
/**
 * Called when a request returns and its response has been parsed into
 * an object.
 *
 * The resulting object may be a dictionary, an array or a string, depending
 * on the format of the API response. If you need access to the raw response,
 * use:
 *
 * (void)request:(FBRequest *)request
 *      didReceiveResponse:(NSURLResponse *)response
 */
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"fb start resonse");
}

/**
 * Called when the Facebook API request has returned a response.
 *
 * This callback gives you access to the raw response. It's called before
 * (void)request:(FBRequest *)request didLoad:(id)result,
 * which is passed the parsed response object.
 */
- (void)request:(FBRequest *)request didLoad:(id)result {
    NSLog(@"fb Result %@",result);
   
    [[[UIAlertView alloc] initWithTitle:@"Successful!"
                                message:@"Your message has been posted"
                               delegate:self
                      cancelButtonTitle:@"OK"
                      otherButtonTitles:nil, nil] show];
}

/**
 * Called when an error prevents the Facebook API request from completing
 * successfully.
 * - (void)request:(FBRequest *)request didFailWithError:(NSError *)error
 */
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"fb Result error");
}

   
#pragma mark - Twittor share
- (void)buttonTwitterSharePressed{
   
    /* --- Set up the message --- */
   
    NSString *strPostOnWall = [stringSubject  stringByAppendingFormat:@" %@",stringMessage];
   
    /* --- If twitter setting available post on twitter --- */
   
    if ([TWTweetComposeViewController canSendTweet]){
       
        TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewController alloc] init];
       
        [tweetSheet setInitialText:strPostOnWall];
       
        /* --- If twitter post canceled or done then this handler will perform --- */
        [tweetSheet setCompletionHandler:
                 ^(TWTweetComposeViewControllerResult result) {
                    
                     if (result == TWTweetComposeViewControllerResultCancelled) {
                         [self twitterPostCancel];     
                     }
                     else if (result == TWTweetComposeViewControllerResultDone){
                         [self twitterPostSuccessfully];
                     }
                    
                     [viewController dismissModalViewControllerAnimated:YES];
                 }];  

        [viewController presentModalViewController:tweetSheet animated:YES];
    }
    /* --- If twitter not configure, jump to configure twitter setting --- */
    else{
       
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]];
    }

}
- (void)twitterPostSuccessfully{
    NSLog(@"Twit posted");
   
    [[[UIAlertView alloc] initWithTitle:@"Successful!"
                                message:@"Your message has been posted"
                               delegate:self
                      cancelButtonTitle:@"OK"
                      otherButtonTitles:nil, nil] show];
   
}
- (void)twitterPostCancel{
    NSLog(@"Twitter cancel");
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    // do something after succefully post
}

@end

No comments:

Post a Comment