How to display the default iOS 6 share action sheet with available share options?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 05:53:36
Mick MacCallum

The UIActivityViewController stated in the other answer makes this trivial. All you have to do is specify the text/image/URL that you want to share and present the activity view controller modally and iOS will automatically display all applicable sharing services. Examples:

Objective-C

- (void)shareText:(NSString *)text andImage:(UIImage *)image andUrl:(URL *)url
{
    NSMutableArray *sharingItems = [NSMutableArray new];

    if (text) {
        [sharingItems addObject:text];
    }
    if (image) {
        [sharingItems addObject:image];
    }
    if (url) {
        [sharingItems addObject:url];
    }

    UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:sharingItems applicationActivities:nil];
    [self presentViewController:activityController animated:YES completion:nil];
}

Swift

func share(sharingText: String?, sharingImage: UIImage?, sharingURL: URL?) {
    let sharingItems:[AnyObject?] = [
                                        sharingText as AnyObject,
                                        sharingImage as AnyObject,
                                        sharingURL as AnyObject
                                    ] 
    let activityViewController = UIActivityViewController(activityItems: sharingItems.compactMap({$0}), applicationActivities: nil)
    if UIDevice.current.userInterfaceIdiom == .pad {
        activityViewController.popoverPresentationController?.sourceView = view
    }
    present(activityViewController, animated: true, completion: nil)
}
Davide

Add this to use the UIActivityViewController.

-(IBAction)shareButtonPressed:(id)sender {

    NSLog(@"shareButton pressed");

    NSString *texttoshare = _txt; //this is your text string to share
    UIImage *imagetoshare = _img; //this is your image to share
    NSArray *activityItems = @[texttoshare, imagetoshare];    
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    activityVC.excludedActivityTypes = @[UIActivityTypeAssignToContact, UIActivityTypePrint];
    [self presentViewController:activityVC animated:TRUE completion:nil];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!