UIActivityViewController customize text based on selected activity

Ertai picture Ertai · Sep 28, 2012 · Viewed 9.8k times · Source

I want to customize text for the same information but when I am sharing it on Facebook I don't want to use the twitter hash tags or @username scheme...

How can I diversify text for sharing based on which sharing service would be used?

Ofcourse I'm using UIActivityViewController:

UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[shareText, shareURL] applicationActivities:nil];

Answer

NickNack picture NickNack · Nov 12, 2012

I took this answer and made a simple class for it. The default message will be seen by sharing outlets other than Twitter, and for Twitter words within the hashWords array will appear with hashes if they are present in the default message. I thought I would share it for anyone else who needs it. Thanks Christopher!

Usage:

TwitterHashActivityItemProvider *twit = [[TwitterHashActivityItemProvider alloc] initWithDefaultText:@"I really like stackoverflow and code"
                                                                                           hashWords:@[@"stackoverflow", @"code"]];
NSArray *items = @[twit];
UIActivityViewController *act = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];

Header:

@interface TwitterHashActivityItemProvider : UIActivityItemProvider

- (id)initWithDefaultText:(NSString*)text hashWords:(NSArray*)hashItems;

@property (nonatomic,strong) NSArray *hashItems;

@end

Implementation:

#import "TwitterHashActivityItemProvider.h"

@implementation TwitterHashActivityItemProvider

- (id)initWithDefaultText:(NSString*)text hashWords:(NSArray*)hashItems;
{
    self = [super initWithPlaceholderItem:text];
    if ( self )
    {
        self.hashItems = hashItems;
    }
    return self;
}

- (id)item
{
    if ( [self.placeholderItem isKindOfClass:[NSString class]] )
    {
        NSString *outputString = [self.placeholderItem copy];

        // twitter gets some hash tags!
        if ( self.activityType == UIActivityTypePostToTwitter )
        {
            // go through each potential hash item and augment the main string
            for ( NSString *hashItem in self.hashItems)
            {
                NSString *hashed = [@"#" stringByAppendingString:hashItem];
                outputString = [outputString stringByReplacingOccurrencesOfString:hashItem withString:hashed];
            }
        }

        return outputString;
    }

    // else we didn't actually provide a string...oops...just return the placeholder
    return self.placeholderItem;
}

@end