App-it.dk

Objective-C, iOS and Web.

Create Custom UIActivity

In iOS 6.0, Apple introduced at new way of sharing information from an iOS app. Using the UIActivityController will bring up an overlay, like the UIActionSheet, but with some default sharing options. These include SMS, Mail, Twitter, Facebook etc.

But what if you want a custom UIActivity that’ll perform a custom action in your application?

Here is an example of how to implement a custom UIActivity:

So basically you’ll have to create a custom class that extends UIActivity, which implements the methods given in the snippet below:

Custom class
1
2
3
4
5
6
7
8
9
10
11
12
#import <UIKit/UIKit.h>
@interface FavoriteActivity : UIActivity

- (NSString *)activityType;
- (NSString *)activityTitle;
- (UIImage *)activityImage;
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems;
- (void)prepareWithActivityItems:(NSArray *)activityItems;
- (UIViewController *)activityViewController;
- (void)performActivity;
- (void)activityDidFinish:(BOOL)completed;
@end
1
- (NSString *)activityTitle;

returns a string that will be displayed as the title in the UIActivityController.

1
- (UIImage *)activityImage;

should return an image that will displayed as a icon in the UIActivityController.

The

1
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems;

should return YES or NO if the given activity items is supported. An example of implementation could be this:

Implementation of canPerformWithActivityItems
1
2
3
4
5
6
7
8
9
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems{
    BOOL canPerform = NO;
    for (id object in activityItems) {
        if ([object isKindOfClass:[SomeClass class]]) {
            canPerform = YES;
        }
    }
    return canPerform;
}

The last methods

1
- (void)performActivity;

and

1
- (void)activityDidFinish:(BOOL)completed;

speaks for them selves.

The activity controller can then be initialized with the custom activity like this:

Initializaing the UIActivityController
1
2
3
4
5
6
7
8
9
CustomActivity *customActivity = [[CustomActivity alloc] init];
__block UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:@[someObject] applicationActivities:@[customActivity]];
activityController.excludedActivityTypes = @[ UIActivityTypePostToWeibo,
UIActivityTypePostToTwitter,
UIActivityTypeAssignToContact];
[self presentViewController:activityController animated:YES completion:^{
    activityController.excludedActivityTypes = nil;
    activityController = nil;
}];

Comments