Search code examples
swiftuipasteboard

Clear UIPasteBoard


Lets assume that 3 strings have been copied on the UIPasteBoard:

UIPasteboard.generalPasteboard().string="hello"
UIPasteboard.generalPasteboard().string="world"
UIPasteboard.generalPasteboard().string="!"

I use UIPasteboard.generalPasteboard().string=""

Will it clear the pasteboard? Is there any similar func for UIPasteBoard like there is clearContents() for NSPasteBoard?


Solution

  • If you know that your program is the only one manipulating the specific pasteboard, then yes, setting the string property to "" will effectively clear the pasteboard.

    You can easily test this in Playground

    var pb = UIPasteboard.generalPasteboard()
    pb.string = "hello"
    pb.string
    pb.items
    pb.string = ""
    pb.string   
    pb.items
    

    which outputs

    <UIPasteboard: 0x7fed6bd0a750>
    <UIPasteboard: 0x7fed6bd0a750>
    "hello"
    [["public.utf8-plain-text": "hello"]]
    <UIPasteboard: 0x7fed6bd0a750>
    nil
    [[:]]
    

    However, note that string property of UIPasteboard is a shorthand for the first pasteboard item that is of type string. All items of type string can be accessed through strings property.

    All underlying pasteboard items are modelled in items property, which is an array of dictionaries of type [String: AnyObject]. Each dictionary contains the type information of an object in the key and pasteboard value in the value.

    Because you are using a system-wide generalPasteboard, it can also be manipulated by other programs, thus, to clear all items from the pasteboard, you should use

    UIPasteboard.generalPasteboard().items = []
    

    If you are using the pasteboard for your internal application purposes, it is better to create an internal pasteboard than to use a system-wide generalPasteboard. See pasteboardWithUniqueName()