UIActivityViewController IOS Tutorial

UIActivityController

In this tutorial, we will learn about UIActivityViewControlleris another nice way for providing user’s with lot of options to do with your app document such as image, text etc. and to share documents via Airdrop, printing document etc. It much more like UIDocumentInteractionController, but offers developer a more control than UIDocumnetInteractionController. If you are not familiar with UIDocumnetInteractionController then you can read it here.

NOTE: Swift version is also available, click here

The main limitations or you can say disadvantages of using the UIDocumentInteractionController are

1)  Provide so many apps list that are capable of handling your document.
2)  Does not provide developers with the functionality to know what activity or option is chosen by  the user.

One of the limitations i encountered in recent time is when I am going to save an image to Photos/photo gallery of the device, I am not able to specify whether user chosen the  option to save in photo gallery or share it other app. Though my requirement is to save image to photo gallery and post it to twitter so I am not worried of other apps installed on device that were capable of handlig my document.’

You can use UIActivityController by simply allocating it and provide an array of documents you want to share.

UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];

UIActivityController initialse

 

With the above line of codes, you are able to present a nice UIActivityController to your user’s.
You can also prevents or limits some of the features to be available to your user’s by passing array of UIActivity to excludedActivityTypes property of UIActivityViewController.

Now let us move further into code for the UIActivityViewController, first we need our document that we want to share in our case its an image. We create an instance of UIImage and named it shareImage. We have  wallpaperImageView as our UIImageView object in which we showed our image.Then we save our image to document directory as we need complete path for the document we want to share.While saving the image to document directory first we remove our old image and the write a new one.This is required if we want to share different images.

UIImage *shareImage = wallpaperImageView.image;
  NSString* imagePath = [NSString stringWithFormat:@”%@/temp.png”,    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
    [[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
    [UIImagePNGRepresentation(shareImage) writeToFile:imagePath atomically:YES];

Saving image to UIDocumentDirectory

 

Now, at this point we have our image path with us and we can give add this image path as an URL to our objectsToShare array. Now create UIActivityController and initalise it with our objectsToShare array. If we want to exclude some of the features such as posting to facebook, posting to vimeo etc. then we can create an array with these UIActivities. Here we created excludedActivities array that contains our prohibited activities. Assign your excludedActivities array to excludedActivityTypes property of UIActivityController. We can also check whether sending file through activity controller succeeded or failed via implementing its completionHandler and check for the BOOL value returned by handler, if its TRUE then its success for us and mission accomplished otherwise failure occurred due to some reasons.Lastly we present our controller.

 NSURL *url = [NSURL fileURLWithPath:imagePath];
    NSArray *objectsToShare = @[url];
    UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    NSArray *excludedActivities = @[UIActivityTypePostToFacebook,
                                    UIActivityTypePostToWeibo,
                                    UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
                                    UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
    controller.excludedActivityTypes = excludedActivities;
    [controller setCompletionHandler:^(NSString *activityType, BOOL completed)
    {
        NSMutableString *messageString = [[NSMutableString alloc]initWithCapacity:0];
        if ([activityType isEqualToString:@”com.apple.UIKit.activity.SaveToCameraRoll”])
        {
            [messageString appendString:@”Image Saved”];
        }
        else if ([activityType isEqualToString:@”com.apple.UIKit.activity.PostToTwitter”])
        {
            [messageString appendString:@”Image posted to twitter”];
        }
        else if ([activityType isEqualToString:@”com.apple.UIKit.activity.Mail”])
        {
            [messageString appendString:@”Image sent by email”];
        }
        else if ([activityType isEqualToString:@”com.apple.UIKit.activity.CopyToPasteboard”])
        {
            [messageString appendString:@”Image copied to pasteboard”];
        }
        else if ([activityType isEqualToString:@”com.apple.UIKit.activity.AssignToContact”])
        {
            [messageString appendString:@”Image assigned to contact”];
        }
        else if ([activityType isEqualToString:@”com.apple.UIKit.activity.Message”])
        {
            [messageString appendString:@”Image sent via message”];
        }
        else if ([activityType isEqualToString:@”com.apple.UIKit.activity.Print”])
        {
            [messageString appendString:@”Image sent to printer”];
        }
       
        if (completed == TRUE)
       {
         UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”Success!” message:messageString delegate:nil cancelButtonTitle:@”Ok” otherButtonTitles: nil];
[alert show];
[alert release];

        }
        [messageString release];
        messageString = nil;
        [controller release];
    }];
    // Present the controller
    [self presentViewController:controller animated:YES completion:nil];

Complete Code for UIActivityController





 

          Source Code: UIActivityController Source Code

Video: