How to Let User Paste Data Into your App in SwiftUI
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.
What are you thoughts about this? Tweet me @franceleonidev and share your opinion.