NSNotificationCenter PasteboardChangedNotification未触发

问题描述 投票:3回答:2

我正在为iOS编写自定义键盘,我想检测用户何时复制一些文本。我已经读过你可以使用NSNotificationCenterUIPasteboardChangedNotification来做到这一点。

但是,当用户复制文本时,我的选择器似乎没有被触发。当我在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
}

谁能确定我错过了什么?

编辑:

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

ios swift keyboard
2个回答
2
投票

我不是一个完美但工作充分的解决方案。我已经在键盘上使用它了。

@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

2
投票

您不能使用NSNotificationCenter,因为键盘扩展是一个不同的过程。

Cocoa包括两种类型的通知中心:NSNotificationCenter类在单个进程中管理通知。 NSDistributedNotificationCenter类管理单台计算机上多个进程的通知。

试试这个解决方案:使用CFNotifications的https://stackoverflow.com/a/28436058/649379。不要忘记启用应用程序组以访问共享容器。

莫尔斯代码在这里:qazxsw poi&qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.