iOS - detect when user copy to clipboard - [UIPasteboard generalPasteboard]
Asked Answered
A

3

8

quick easy question

while using a WebView with some text in it - the user can select a snippet of text from it and press a UIButton which I created - running the following action:

-(IBAction)copyToClip
{
    NSString *copyClip = [UIPasteboard generalPasteboard].string;
    NSLog(@"Clip = %@",copyClip);
    // (works fine)
}

I would like to call the same function without a UIButton, thus when the user did a "copy" action it will activate the above code. (I assume a listener)

what would be the appropriate listener for this?

Andyane answered 20/1, 2012 at 13:3 Comment(1)
have you check these notifications:#4240587 ?Sherfield
E
16

Use NSNotificationCenter and register for UIPasteboardChangedNotification: http://developer.apple.com/library/IOs/documentation/UIKit/Reference/UIPasteboard_Class/Reference.html#//apple_ref/c/data/UIPasteboardChangedNotification

[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(copyToClip) name:UIPasteboardChangedNotification object:nil];
Eogene answered 20/1, 2012 at 13:29 Comment(2)
Hey, Is it working when user get copy any thing in any other app.Mella
What about Swift 4 version?Aramanta
E
0

If someone is interested in the Xamarin/C# version:

NSNotificationCenter.DefaultCenter.AddObserver(UIPasteboard.ChangedNotification, 
            notification => { 
                // custom code here
            });
Edgardo answered 23/6, 2020 at 8:49 Comment(0)
R
0

Swift 5

UIPasteboard.changedNotification

NotificationCenter.default.addObserver(self, selector: #selector(handleCopy), name: UIPasteboard.changedNotification, object: nil)

@objc func handleCopy(sender: NSNotification) {
    // Handle new pasteboard
    print("pasteboard changed: \(UIPasteboard.general.items.first)")
}

Don't forget to add @objc to your handler so the method is visible to the objective-C selector.

Ratel answered 21/8, 2023 at 21:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.