How to Use UIPasteBoard to Implement Custom Copy and Paste In Your App

by  on OCTOBER 26, 2009 in NEWS

Finally, we can share data between our apps using custom copy and paste in the latest version of iPhone OS. Here is how you do it!

Copy and Paste in UIKit

As you know many of the controls in UIKit now come pre-loaded with the ability to copy and paste text. You can also use this new ability in your own apps to copy and paste other things including: images, SQLite databases, text or any file. This is a great way to share data between your apps if you want to provide users with a suite of apps with integrated functionality.

…also, it is very easy. Check out the video below:
Implementing UIPasteBoard

http://content.screencast.com/users/AppShop/folders/Jing/media/ea69399f-824a-4d98-b9d8-626cfe74ef30/jingh264player.swf

CopyFrom Source Code

-(IBAction)copyImageToPasteBoard{
	UIPasteboard *appPasteBoard = [UIPasteboard pasteboardWithName:@"CopyFrom" create:YES];
	appPasteBoard.persistent = YES;

	NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"Old-Time-Photo.jpg"]);
	[appPasteBoard setData:data forPasteboardType:@"com.appshop.copyfrom.imagedata"];
}

-(IBAction)copyStringToPasteBoard{
	UIPasteboard *appPasteBoard = [UIPasteboard pasteboardWithName:@"CopyFrom" create:YES];
	appPasteBoard.persistent = YES;
	[appPasteBoard setString:textView.text];
}

PasteTo Source Code

-(IBAction)pasteImageToPasteBoard{
	UIPasteboard *appPasteBoard = [UIPasteboard pasteboardWithName:@"CopyFrom" create:YES];
	NSData *data = [appPasteBoard dataForPasteboardType:@"com.appshop.copyfrom.imagedata"];
	imageView.image = [UIImage imageWithData:data];
}

-(IBAction)pasteStringToPasteBoard{
	UIPasteboard *appPasteBoard = [UIPasteboard pasteboardWithName:@"CopyFrom" create:YES];
	textView.text = [appPasteBoard string];
}

 

Recap

Using UIPasteBoard in iPhone programming is amazingly simple and opens up some possibilities that we did not have a year ago. To use UIPasteBoard you simply create a instance using pasteboardWithName, put stuff into the paste board and then set the persistant property equal to YES. Then any app can get a reference to your paste board and use the data contained within. You can use it for simple strings and even data that you can put into NSData like SQLite databases.

Advertisements