Mastering Copy and Paste in iOS – Part 1

System wide copy and paste is built into most of the stock iOS controls without the developer having to do any extra work to enable the feature.  Sometimes for security purposes you may wish to lock down the functionality (to not allow copy and paste at all) or disallow copying and pasting between your app and other apps that may be on the device.  Restricting this functionality is a pretty common requirement for the growing market of security frameworks out there for enterprise applications such as GOOD and MobileIron.  They commonly refer to this as “data leakage”.

In this 3-part series I’ll explore the copy and paste system in iOS and how you can use it to fit the needs of your specific application.

This first part will focus on locking down the copy and paste system completely.

In the second part I’ll show you how you can create an application specific pasteboard to allow copy and paste within your own application while still preventing data leakage to other apps as well as posting other types of data to UIPasteboard.

In the third part I’ll explore other types of data on the pasteboard with simple drawing sample app.

Locking down copy and paste

All controls in UIKit expose a single method you can override to control actions such as copy and paste..  To lock down system wide we really only need to implement a category on the specific controls.  In preparing the sample code for this I attempted a category on UIResponder, but that seems to have unintended side effects. Adding it to the classes directly seemed to be the most consistent approach.

At a high level you’ll want to use code like this:

@interface UITextField (lockdown) @end
@implementation UITextField (lockdown)
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    SEL copy = @selector(copy:);
    SEL cut = @selector(cut:);
    SEL paste = @selector(paste:);
    if (action == copy ||
        action == cut ||
        action == paste)
    {
        return NO;
    }
    return YES;
}
@end

You can find the sample code for this here that will lock down UITextField, UITextView, and UISearchBar.  Remember that since this method exists on UIResponder, you can use it to lock down any control, even complex ones like UIWebView.

One more note:

When you first implement this you may notice that you get a compiler warning about reimplementing a method in a category that already has an implementation elsewhere.

You can prevent this code by wrapping it in the following:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
// ...
#pragma clang diagnostic pop

Be sure to check out part 2 of this series for digging deeper into copy and paste and the UIResponderStandardEditActions protocol.

Posted on May 22, 2013, in Code, Tutorials and tagged , , , , . Bookmark the permalink. 1 Comment.

Leave a comment