Kevin McMahon

Enthusiast

Blog Search

MonoTouch Quickie : UIPasteboard Snippet

Came across the need to plop a string onto the clipboard (aka UIPasteboard) programatically last night and hit up the MonoTouch docs to see what was involved. It wasn’t readily apparent what would work for the string expected to be passed as the SetValue method pasteboardType argument. Turns out, after digging into the official Apple docs, the string you need to provide is the Uniform Type Identifier (UTI) that corresponds to the data type being passed (in my case “public.utf8-plain-text”). For my future reference (always seems to take longer to find things at the iPhone doc site) here is a table of the relevant UTIs that might come in handy in the future.

string public.utf8-plain-text
JPEG public.jpeg
PNG public.png
Url public.url

And for good measure here is a snippet that shows putting a string on the general clipboard and reading it off.

string clipboardText = "Copy and Paste Me!";
UIPasteboard.General.SetValue(new NSString(clipboardText),"public.utf8-plain-text");

string actualClipboardText = UIPasteboard.General.GetValue("public.utf8-plain-text");
Assert.AreSame( clipboardText, actualClipboardText.ToString());

Enjoy.

Updated 1/30/2010: Replaced NSStrings with strings
Updated 6/28/2012: Updated SetValue call to wrap up the C# string into an NSString as the API takes an NSObject now.