iOS UIPasteboard

Filed Under: iOS

In this tutorial, we’ll be discussing and implementing the UIPasteboard class in our iOS Application.

UIPasteboard

The UIPasteboard class provides a clipboard and is used to share data within the app and from one application to the other.

Using a UIPasteboard, you can copy paste text, url, images and other data types. UIPasteboard has a system-wide clipboard which holds the data you’ve copied.

Following are the important helper properties and functions of a UIPasteboard:

general property is used to retrieve the system-wide UIPasteboard.


let pasteboard = UIPasteboard.general

Creating your own Named Pasteboard:


let pasteboard = UIPasteboard.init(name: UIPasteboard.Name(rawValue: "pasteboard_name"), create: true)

Inside the init method, we pass two arguments: name and create.
Using the above statement we can retrieve the same named Pasteboard.

The create argument requires a Bool value. If it is set as true, then the Pasteboard would be created if it doesn’t exist already.

UIPasteboard.withUniqueName() returns a unique UIPasteboard. This returns a Pasteboard which is visible in all your apps having the same APP ID.

To copy a String/URL/UIColor/UIImage to the Pasteboard, we simply do:


UIPasteboard.general.string = "String"
UIPasteboard.general.url = URL(string: "http://www.google.com")
UIPasteboard.general.color = UIColor.red
UIPasteboard.general.image = UIImage(named : "sample.png")
In order to pass more than one values we can use the properties strings, colors, urls, images

We can set values to the Named Pasteboard, or even the general pasteboard instance using the following functions as well:

  • func setValue(Any, forPasteboardType: String) – This is used to set any instance such as string, date, url, model object. We pass the type of the value in the second argument.
  • func setData(Data, forPasteboardType: String) – This is used to set Data which is generally an image/video or a File type.

The following functions return the data for the type passed in:

  • func data(forPasteboardType: String) -> Data?
  • func value(forPasteboardType: String) -> Any?

func itemSet(withPasteboardTypes: [String]) -> IndexSet? returns a Set containing values of all the types passed in the array.

In order to check whether the Pasteboard has a value of the certain type we can do:

  • pasteboard.hasStrings
  • pasteboard.hasURLs
  • pasteboard.hasColors
  • pasteboard.hasImages

func setItems([[String : Any]], options: [UIPasteboard.OptionsKey : Any] = [:]) is used to add a dictionary of items to the Pasteboard. We can set privacy options on the items as well The options arguments is a dictionary of key-value pairs as well. Following are the two most commonly used options:

  • expiration – The date after which the items would be cleared from the Pasteboard
  • localOnly – By default the Pasteboard is universal. That means, if the handoff feature is enabled on your iOS Device, the pasteboard can be used across your Apple Devices. To keep the Pasteboard restricted in your current device only, set localOnly to true

In the next section, we’ll be creating an iOS Application with the above-learned methods and properties in use:

Project Storyboard

Our ViewController UI consists of UIStackViews with nested StackViews as shown in the Storyboard below:

ios uipasteboard storyboard

We’ll be doing copy paste of String, URL and an Image that we’ve added in the assets folder.

  • Top StackView – Consists of UITextField. Here the copy paste would be done on String type.
  • Middle StackView – Consists of UILabel. Here the copy paste would be done on URL type.
  • Bottom StackView – Consists of UIImage. Here the copy paste would be done on Image type.

Code

The code for the ViewController.swift class is given below:


import UIKit
import MobileCoreServices

class ViewController: UIViewController {

    @IBOutlet weak var textFieldCopy: UITextField!
    @IBOutlet weak var textFieldPaste: UITextField!
    @IBOutlet weak var labelCopy: UILabel!
    @IBOutlet weak var labelPaste: UILabel!
    @IBOutlet weak var imageCopy: UIImageView!
    @IBOutlet weak var imagePaste: UIImageView!

    @IBAction func btnCopyStringAction(_ sender: Any) {
        
        UIPasteboard.general.string = textFieldCopy.text
        
    }
    
    
    @IBAction func btnPasteStringAction(_ sender: Any) {
        
        textFieldPaste.text = textFieldPaste.text! + UIPasteboard.general.string!
    }
    
    @IBAction func btnCopyUrlAction(_ sender: Any) {
        
        let oneHour = Date().addingTimeInterval(60 * 60)
        
        let pasteboard =  UIPasteboard.init(name: UIPasteboard.Name(rawValue: "sample_pasteboard"), create: true)
        pasteboard?.setItems([], options: [UIPasteboard.OptionsKey.localOnly : true, UIPasteboard.OptionsKey.expirationDate : oneHour])
        pasteboard?.setValue(URL(string: labelCopy!.text!) ?? "", forPasteboardType: kUTTypeURL as String)
    
    }
    
    @IBAction func btnPasteUrlAction(_ sender: Any) {
        
        let pasteboard = UIPasteboard.init(name: UIPasteboard.Name(rawValue: "sample_pasteboard"), create: true)
        labelPaste.text = pasteboard?.url?.absoluteString
    }
    
    @IBAction func btnCopyImageAction(_ sender: Any) {
        
        let image = imageCopy.image!
        if let data = image.pngData() {
            UIPasteboard.general.setData(data,forPasteboardType: kUTTypePNG as String)
        }
        
    }
    
    @IBAction func btnPasteImageAction(_ sender: Any) {
        
        
        let pasteboard = UIPasteboard.general
    
        let imageTypes = UIPasteboard.typeListImage as! [String]
        
        if pasteboard.contains(pasteboardTypes: imageTypes) {
            for imageType in imageTypes {
                if let data = pasteboard.data(forPasteboardType: imageType) {
                    if let pasteThisImage = UIImage(data: data) {
                        imagePaste.image = pasteThisImage
                        break
                    }
                }
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

We’ve imported MobileCoreServices which is used to set the types of the data.

In the Top StackView, we have two UITextField. We copy the string from one to the other.
In the Middle StackView, we copy the URL from a label to the other.

To convert a string to a URL:
URL(string: String)

Vice-versa:
URL.absoluteString

In the Middle StackView, we’ve created a named Pasteboard. The type of the value set is kUTTypeURL. We’ve set the expiry to an hour and set the Pasteboard as localOnly.

In the Bottom StackView, we copy an image by using pngData() to get the Data instance out of the image and set it in the setData() on the Pasteboard instance.
UIPasteboard.typeListImage is used to retrieve all the types of items in the Pasteboard.

The output of the application in action is given below:

ios uipasteboard output

This brings an end to this tutorial. You can download the project from the link below:

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages