Search code examples
iosmfmailcomposeviewcontroller3dtouch

UIPreviewAction to Mail From Peek


I am working on implementing Peek and Pop in my app, along with UIPreviewActions to it. I have my PreviewView all set up, and both Peek and Pop work great, my issue is with adding UIPreviewActions to it. Of course, you have to put the UIPreviewAction method within the preview controller, so how do you get it to then dismiss that view, and open the view within its parent controller?

I have in the PreviewController:

- (NSArray*)previewActionItems {

    // setup a list of preview actions
    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"Post to Facebook" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {


    }];

    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"Message" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {


    }];

    UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"Email" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        [self displayComposerSheet];


    }];

    // add them to an arrary
    NSArray *actions = @[action1, action2, action3];

    // and return them
    return actions;
}

displayComposerSheet is just a standard method for composing email, that includes the self presentViewController method for displaying it. However, all of this method is within the PreviewController, but the Mail composer technically needs to launch from the TableView where all this is located. How should I go about doing this?


Solution

  • You can achieve this by either Protocol or NSNotification. You need to call the controller (TableView controller) method from displayComposerSheet method.

    Example with protocol:

    1 - Create protocol in PreviewController:

    @protocol PreviewControllerDelegate <NSObject>
    - (void) sendEmail;
    @end
    

    2 - Create property in PreviewController as:

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

    3 - Call delegate method from action method:

    -(void) displayComposerSheet
    {
        [self.delegate sendEmail];
    }
    

    4 - Set PreviewController delegate property before loading it in UIViewControllerPreviewingDelegate method

    - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
    

    5 - Implement sendEmail method in the controller (TableView Controller) from which you can show the mail composer.