NSNotificationCenter PasteboardChangedNotification Not Firing

前端 未结 2 1733
死守一世寂寞
死守一世寂寞 2021-02-10 11:15

I\'m writing a custom keyboard for iOS and I\'d like to detect when the user copies some text. I\'ve read that you can use the NSNotificationCenter along with

2条回答
  •  终归单人心
    2021-02-10 12:16

    My not a perfect but work enough solution. I already use it in keyboard.

    @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
    

提交回复
热议问题