How to Let User Paste Data Into your App in SwiftUI

Discover the handy PasteButton available in iOS 16 and SwiftUI, that will allow users to easily paste content in your app.

Francesco Leoni

1 min read

Availability

iOS 16

macOS 10.15

With iOS 16, SwiftUI has a new dedicated PasteButton that lets user paste any kind of objects.

It let us receive any object that conforms to the Transferable protocol. Some examples are: String, URL, Data and Image.

Implementation

To let the user paste an image, you can set the payloadType to Data.self and then convert the Data to a UIImage and then use this image to create an Image.

PasteButton(payloadType: Data.self) { data in

guard let imageData = data.first else { return }

self.image = Image(uiImage: UIImage(data: imageData) ?? UIImage())

}

Or, with a more straightforward implementation.

PasteButton(payloadType: Image.self) { images in

guard let image = images.first else { return }

self.image = image

}

If you need a more fine grained filter for the objects that the user is allowed to paste, you can use the init(supportedContentTypes:).

In this example we allow the user to paste only xml files.

PasteButton(supportedContentTypes: [.xml]) { providers in

for provider in providers {

let progress = provider.loadFileRepresentation(for: .xml) { url, openInPlace, error in

if let url {

try? String(contentsOf: url)

}

}

}

}

Note

The input into the closure is an array of objects or providers not a single one.

Behaviour

The button dims itself if no object that matches the declared type is present in the user's clipboard.

If you have any question about this article, feel free to email me or tweet me @franceleonidev and share your opinion.

Thank you for reading and see you in the next article!

Share this article

Related articles


Combine CoreData and SwiftUI

See how to use CoreData database with SwiftUI. Syncing changes from CoreData to every View of your app.

5 min read

SwiftUICoreData

SwiftData the Successor of CoreData Explained with SwiftUI

Discover the SwiftData framework built on top of CoreData. Save and fetch data locally. Available for Xcode 15, Swift and SwiftUI.

5 min read

SwiftUICoreData

Make your Chart Scrollable with SwiftUI Charts (iOS 17)

Discover the new SwiftUI Charts APIs that enables you to create scrollable chart easily. Available for Xcode 15 and iOS 17.

2 min read

ChartsSwiftUI