Search code examples
iosobjective-cuiactivityviewcontroller

IOS/Objective-C: UIActivityViewController: Customize for different Activity Types


I am trying to customize the content shared using the UIActivityViewController. The method suggested in some blog posts and answers on SO is to subclass UIActivityItemProvideras below. Some answers also say that the class should adopt a protocol UIActivityItemSource but I am fuzzy on what the protocol has to do with the Provider.

My code is in a view controller class which I have made accept the <UIActivityItemSource Protocol> in the .h file. I have also placed the following method in the .m file along with similar methods for message, placeholder, URL and thumbnail. However, they are not having any effect on the content shared which is the same for all the types, message, email, Facebook, etc.

What am I missing?

-(NSString *)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(UIActivityType)activityType
{
    if (activityType == UIActivityTypeMessage) {
        return @"My message subject";
    } else if (activityType == UIActivityTypeMail) {
        return @"My mail subject";
    }
    return @"My subject otherwise";
}

Edit:

The following code works fine to send identical content to different activities. But the above methods are evidently necessary to customize:

NSArray *activityItems = @[text,url];
        UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems: activityItems applicationActivities:nil];
        activityViewController.excludedActivityTypes = @[UIActivityTypePostToWeibo,UIActivityTypePrint,UIActivityTypeCopyToPasteboard,UIActivityTypeSaveToCameraRoll];
    [activityViewController setValue:_dare.shtodo forKey:@"Did you see this?"];

        [self presentViewController:activityViewController animated:YES completion:nil];

Thanks in advance for any suggestions on what I might be missing to get this to work.


Solution

  • You need to pass an instance or instances of your class that implements UIActivityItemSource when creating a UIActivityViewController with initWithActivityItems:applicationActivities: - see the documentation here. A view controller is probably not a good choice for this, I'd instead make dedicated objects to do this. Ultimately your code could look something like:

    MySourceClass *mySource = [MySourceClass new];
    NSArray *activityItems = @[mySource];
    UIActivityViewController *activityViewController =
        [[UIActivityViewController alloc] initWithActivityItems:activityItems
                                          applicationActivities:nil];