ThE uSeFuL
ThE uSeFuL

Reputation: 1534

Intercept paste action in a UIWebView (Swift)

Is there a way in Swift to get the pasted content before it is pasted? Ideally I should be to read the to be pasted content when user selects 'paste' from the default pop-up menu in an editable element. Right now I'm looking at a UIWebView with the a content editable div.

Code I have so far (inspired by Ludovic's answer)

class myWebView: UIWebView {

        override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        print(action)

        return super.canPerformAction(action, withSender: sender)
    }

}

Output (every time I tap on the content editable div):

cut: copy: select: selectAll: delete: _promptForReplace: _transliterateChinese: _showTextStyleOptions: _lookup: _define: _addShortcut: _accessibilitySpeak: _accessibilitySpeakLanguageSelection: _accessibilityPauseSpeaking: _share: makeTextWritingDirectionRightToLeft: makeTextWritingDirectionLeftToRight:

Eventhough paste selector is not listed here it is available in the popup menu.

Upvotes: 2

Views: 999

Answers (3)

arunjos007
arunjos007

Reputation: 4355

Objective C

CLS_LOG(@"copied test %@",[[UIPasteboard generalPasteboard] string]);

Swift

print("String is \(UIPasteboard.general.string)")

Upvotes: 1

Ludovic
Ludovic

Reputation: 2002

You should override the canPerformAction method to catch action

override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(paste(_:)) {
        // Do something
        return false // Will disable paste action
    }

    return super.canPerformAction(action, withSender: sender)  
}

You can extend all UITextField to have this feature everywhere in your app or create a custom CatchPasteTextField to have this feature only for a given UITextField class

Upvotes: 0

Ram
Ram

Reputation: 969

You can get the pasted content before it paste as

let pasteboardString: String? = UIPasteboard.general.string
if let theString = pasteboardString {
    print("String is \(theString)")
}

Upvotes: 1

Related Questions