Use PasteButton In SwiftUI To Handle Any UTType

Daily Coding Tip 021

A version of this tip appeared in the documentation I wrote for Views and Controls in SwiftUI.


This control allows you to paste information on MacOS, but it is not available on iOS. It can take a variety of data types, which are expressed as UTIs. To quote Apple’s documentation, “Uniform Type Identifiers declares common types for resources to be loaded, saved, or opened from other apps.” In Xcode 11, it was necessary to provide these strings in an array when creating a PasteButton.

I’ve included a function called getUTiTypeString in my example that lets you find the UTI string for any type, which will probably help you when implementing this button.

Now we have a new structure called UTType, which makes it a lot easier to create the types that you want to support. You can either pass the initializer for this structure a string that would’ve worked in Xcode 11, or you can use one of the many system-declared types that are provided.

The initializer that takes a string returns an optional, so if you use it you have to be sure that the string you use is correct. I have used UTType.text for my example, but I included an example below that constructed it manually from a string. Note that it is not recommended to force unwrap an optional using the exclamation mark. I just wanted to show that the UTType you get from the system declared type is not nil, so neither would the equivalent constructed from a string.

Here’s an example that uses my PasteButtonView in combination with a multiline TextEditor:

Once you have decided what type identifiers you need, you will need to handle the data that you get from the NSItemProvider. My example only pastes the first item in the array, but hopefully, it makes it clear how you could handle other data types and multiple items.

Here’s a list of the types that conform to NSItemProviderWriting, and can therefore be used for pasting with the PasteButton:

You can also conform to this protocol with your own custom types, allowing you to paste custom types of data.


Get more Daily Coding Tips in your inbox!