Xcode : sharing content via Action Sheet

Miwi picture Miwi · Aug 11, 2015 · Viewed 39.4k times · Source

I would like to replicate this behaviour (see image below) and share contents from my app using this kind of action sheet.

enter image description here

The question is:

Is this really an Action Sheet? I can't find anywhere tutorial for iOS 7 or 8. Not sure how to proceed.

Do the sharing options depends on user's configurations?

Hints would be appreciated.

Answer

Anbu.Karthik picture Anbu.Karthik · Aug 11, 2015

It is not in UIActionSheet it is in UIActivityController, which is the default function in iOS.

objective-C

- (void)presentActivityController:(UIActivityViewController *)controller {

    // for iPad: make the presentation a Popover
    controller.modalPresentationStyle = UIModalPresentationPopover;
    [self presentViewController:controller animated:YES completion:nil];

    UIPopoverPresentationController *popController = [controller popoverPresentationController];
    popController.permittedArrowDirections = UIPopoverArrowDirectionAny;
    popController.barButtonItem = self.navigationItem.leftBarButtonItem;

    // access the completion handler
    controller.completionWithItemsHandler = ^(NSString *activityType,
                                              BOOL completed,
                                              NSArray *returnedItems,
                                              NSError *error){
        // react to the completion
        if (completed) {
            // user shared an item
            NSLog(@"We used activity type%@", activityType);
        } else {
            // user cancelled
            NSLog(@"We didn't want to share anything after all.");
        }

        if (error) {
            NSLog(@"An Error occured: %@, %@", error.localizedDescription, error.localizedFailureReason);
        }
    };
}

-(void)sendMessage {
    //create a message
    NSString *theMessage = @"Some text we're sharing with an activity controller";
    NSArray *items = @[theMessage];

    // build an activity view controller
    UIActivityViewController *controller = [[UIActivityViewController alloc]initWithActivityItems:items applicationActivities:nil];

    // and present it
    [self presentActivityController:controller];
}

Swift

let shareText = "Hello, world!"

if let image = UIImage(named: "myImage") {
    let vc = UIActivityViewController(activityItems: [shareText, image], applicationActivities: [])
     present(vc, animated: true, completion: nil)
}

Try these links for tutorials

  1. http://nshipster.com/uiactivityviewcontroller/

  2. http://www.codingexplorer.com/add-sharing-to-your-app-via-uiactivityviewcontroller/

  3. http://roadfiresoftware.com/2014/02/how-to-add-facebook-and-twitter-sharing-to-an-ios-app/

Swift

https://www.hackingwithswift.com/example-code/uikit/how-to-share-content-with-uiactivityviewcontroller