Search code examples
iosswiftuipasteboard

UIPasteboard – Set copied text to expire


I have a string that I want to put into UIPasteboard and it should expire after 2 minutes

UIPasteboard.general.setObjects(objects: [NSItemProviderWriting],
    localOnly: true, 
    expirationDate: Date().addingTimeInterval(120))

What should be the value of the objects key?


Solution

  • You should implement the interface NSItemProviderWriting and its required methods in one of your controller classes.

    A very simple implementation could look like where yourString contains the string to paste:

    static var writableTypeIdentifiersForItemProvider: [String] {
        return [ kUTTypeUTF8PlainText as String ]
    }
    
    func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping (Data?, Error?) -> Void) -> Progress? {
        completionHandler(yourString.data(using: .utf8), nil)
        return nil
    }
    

    You should add import MobileCoreServices for importing the definition of kUTTypeUTF8PlainText.

    Typically, for this implementation you use the controller which makes the call in your example code above. Then, you should use this as as value in the array:

    UIPasteboard.general.setObjects(objects: [ self ],
        localOnly: true, 
        expirationDate: Date(timeIntervalSinceNow: 120))