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

chewy picture chewy · Jan 20, 2012 · Viewed 12.2k times · Source

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?

Answer

user529758 picture user529758 · Jan 20, 2012

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];