NSNotificationCenter PasteboardChangedNotification不触发

mev*_*son 5 keyboard ios swift

我正在为iOS编写一个自定义键盘,我想检测用户何时复制一些文本。我读过您可以使用和NSNotificationCenter一起UIPasteboardChangedNotification执行此操作。

但是,当用户复制文本时,似乎没有触发我的选择器。当我addObserver在线路上放置一个断点时,尽管击中前后的断点似乎都被跳过了。这是我正在使用的代码:

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

    // Register copy notifications 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleCopy:", name: UIPasteboardChangedNotification, object: nil)
}


func handleCopy(sender: NSNotification) {
//todo: handle the copied text event
}
Run Code Online (Sandbox Code Playgroud)

谁能确定我所缺少的吗?

编辑:

我注意到,如果我在注册通知后以编程方式更新粘贴板,则会触发该通知,但是如果用户使用上下文菜单“复制”,我仍然无法弄清为什么没有被点击。

WIN*_*gey 4

我的解决方案不是完美但足够工作。我已经在键盘中使用它了。

@interface MyPrettyClass : UIViewController

@end

@implementation MyPrettyClass

@property (strong, nonatomic) NSTimer   *pasteboardCheckTimer;
@property (assign, nonatomic) NSUInteger pasteboardchangeCount;

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    _pasteboardchangeCount = [[UIPasteboard generalPasteboard] changeCount];


    //Start monitoring the paste board
    _pasteboardCheckTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                             target:self
                                                           selector:@selector(monitorBoard:)
                                                           userInfo:nil
                                                            repeats:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];

    [self stopCheckingPasteboard];
}

#pragma mark - Background UIPasteboard periodical check

- (void) stopCheckingPasteboard{

    [_pasteboardCheckTimer invalidate];
    _pasteboardCheckTimer = nil;
}

- (void) monitorBoard:(NSTimer*)timer{

    NSUInteger changeCount = [[UIPasteboard generalPasteboard]; changeCount];
    if (changeCount != _pasteboardchangeCount) { // means pasteboard was changed

        _pasteboardchangeCount = changeCount;
        //Check what is on the paste board
        if ([_pasteboard containsPasteboardTypes:pasteboardTypes()]){

            NSString *newContent = [UIPasteboard generalPasteboard].string;

            _pasteboardContent = newContent;

            [self tryToDoSomethingWithTextContent:newContent];
        }
    }
}

- (void)tryToDoSomethingWithTextContent:(NSString)newContent{
    NSLog(@"Content was changed to: %@",newContent);
}

@end
Run Code Online (Sandbox Code Playgroud)