UIPasteboard is a built-in API that allows you to copy items to the pasteboard in iOS. A user then taps the blinking cursor into any field where text and images are allowed and “pastes” the contents currently in the pasteboard. Since this function can be very helpful, here is a simple tutorial on the ways to implement UIPasteboard in Xcode.
First Things First
The first step to using the UIPasteboard is to include the MobileCoreServices.framework into your project. This is done by importing it into the header file of the class you intend to use:
Working with Text
Copying text is super simple. Just add these lines into the button action where you want to copy the text:
NSString *stringYouWantToCopy = @”Hey there.”;
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard setString: stringYouWantToCopy];
Working with Images – Before iOS 6
With images before iOS 6, all that was needed something like this:
UIPasteboard *appPasteBoard = [UIPasteboard pasteboardWithName:@”CopyFrom” create:YES];
appPasteBoard.persistent = YES;
NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@”image.jpg”]);
[appPasteBoard setData:data forPasteboardType:@”com.app.imagedata”];
Working with Images – After iOS 6
Now with iOS 6 and later, these lines of code will no longer work. If you were to use them, the image would not be copied and the user would receive a question mark (?) when they tried to paste the image in the desired location.
How do I know? It took hours of frustration and seeing that question mark! But finally I found the solution and hopefully, it will help you avoid the same mistake.
The solution is to run a for loop for each image to be copied with this code:
NSData* imageData = UIImageJPEGRepresentation(img, 1);
NSMutableDictionary *item = [NSMutableDictionary dictionary];
[item setValue:imageData forKey:(NSString*)kUTTypeJPEG];
[[UIPasteboard generalPasteboard] addItems:[NSArray arrayWithObject:item]];
Have any questions after giving this a try? Please feel free to submit your questions or comments below.