Subclassing and Using UIActivityItemProvider Using a UIActivityViewController

Finally, I will find someone who is facing the same problem as me.

UIActivityViewController customizes text based on selected action

I want to configure a content share using UIActivityViewController actions. A good answer is:

"Instead of passing text strings to the initWithActivityItems call, pass in your own class of the UIActivityItemProvider class and when you implement the itemForActivityType method, it will provide the exchange service as the" activityType "parameter.

You can then return the customized content from this method.

I understand the tricks, but I can’t do it ...

I did this as a subclass:

@interface SharingItems : UIActivityItemProvider @implementation SharingItems -(id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType { // Here depending on the activityType i want to share NSString or UIImage } @end 

But I do not know what to do now in my original viewController:

 -(void)actionSheet { if ([[UIActivityViewController class] respondsToSelector:@selector(alloc)]) { __block NSString *imgName = [[NSString alloc] initWithFormat:@"%@", _sharingUrl]; NSArray *activityItems = [NSArray arrayWithObjects:imgName, nil]; UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil]; [self presentViewController:activityController animated:YES completion:nil]; __block NSString *chan = [[NSString alloc] initWithFormat:@"%@", _channel]; [activityController setCompletionHandler:^(NSString* activityType, BOOL completed) { if (completed) { } }]; } else [self displayActionSheet]; } 
+6
source share
1 answer

Here is an example of UIActivityItemProvider (not tested, but adapted from working code):

 @implementation StringProvider - (id)initWithPlaceholderString:(NSString*)placeholder facebookString:(NSString*)facebookString { self = [super initWithPlaceholderItem:placeholder]; if (self) { _facebookString = facebookString; } return self; } - (id)item { if ([self.activityType isEqualToString:UIActivityTypePostToFacebook]) { return _facebookString; } else { return self.placeholderItem; } } @end 

Then, when you configure the activity controller:

 StringProvider *stringProvider = [[StringProvider alloc] initWithPlaceholderString:@"Default string" facebookString:@"Hello, Facebook."]; UIActivityViewController *shareController = [[UIActivityViewController alloc] initWithActivityItems:@[stringProvider] applicationActivities:nil]; 

Basically, you create UIActivityItemProviders that provide the necessary data when the element method (id) is called and passed to these activity element providers when creating the activity type controller. You need to initialize the placeholder so that the OS knows which class will be the last (most likely, NSString, NSURL, UIImage). Hope this helps!

+15
source

All Articles