首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在后台接收UIPasteboard (generalPasteboard)通知

在后台接收UIPasteboard (generalPasteboard)通知
EN

Stack Overflow用户
提问于 2010-11-21 20:12:49
回答 1查看 8.2K关注 0票数 13

有办法这么做吗?我在启动时为UIPasteboardChangedNotification注册了对象,但是当将对象发送到后台并打开(例如) Safari并复制一些文本时,我的处理程序就不会被调用。(我现在只使用模拟器)。

我用过两种方法:

代码语言:javascript
运行
复制
[[NSNotificationCenter defaultCenter] addObserver:self 
    selector:@selector(pasteboardNotificationReceived:) 
    name:UIPasteboardChangedNotification 
    object:[UIPasteboard generalPasteboard]];

以及:

代码语言:javascript
运行
复制
[[NSNotificationCenter defaultCenter] addObserver:self 
    selector:@selector(pasteboardNotificationReceived:) 
    name:UIPasteboardChangedNotification 
    object:nil ];

注册我的处理程序。

EN

回答 1

Stack Overflow用户

发布于 2011-03-15 17:15:48

我也有同样的问题。根据UIPasteboard类引用属性的changeCount文档(重点是我的):

每当粘贴板的内容发生变化时--特别是当添加、修改或删除粘贴板项时--UIPasteboard就会增加此属性的值。在增加更改计数之后,UIPasteboard发布名为UIPasteboardChangedNotification (用于添加和修改)和UIPasteboardRemovedNotification (用于删除)的通知。..。当应用程序重新激活时,类还更新更改计数,而另一个应用程序已经更改了pasteboard内容。当用户重新启动设备时,将更改计数重置为零。

我读到这意味着我的应用程序被重新激活后,我的应用程序就会收到UIPasteboardChangedNotification通知。然而,仔细阅读就会发现,只有当应用程序被重新激活时才会更新changeCount

我处理这个问题的方法是在我的应用程序委托中跟踪黑板的changeCount,并在应用程序处于后台时发布预期的通知,当我发现changeCount已经被更改时。

在应用程序委托接口中:

代码语言:javascript
运行
复制
NSUInteger pasteboardChangeCount_;

在应用程序代表的实现中:

代码语言:javascript
运行
复制
- (BOOL)application:(UIApplication*)application
    didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  [[NSNotificationCenter defaultCenter]
   addObserver:self
   selector:@selector(pasteboardChangedNotification:)
   name:UIPasteboardChangedNotification
   object:[UIPasteboard generalPasteboard]];
  [[NSNotificationCenter defaultCenter]
   addObserver:self
   selector:@selector(pasteboardChangedNotification:)
   name:UIPasteboardRemovedNotification
   object:[UIPasteboard generalPasteboard]];

  ...
}

- (void)pasteboardChangedNotification:(NSNotification*)notification {
  pasteboardChangeCount_ = [UIPasteboard generalPasteboard].changeCount;
}

- (void)applicationDidBecomeActive:(UIApplication*)application {
  if (pasteboardChangeCount_ != [UIPasteboard generalPasteboard].changeCount) {
    [[NSNotificationCenter defaultCenter] 
     postNotificationName:UIPasteboardChangedNotification
     object:[UIPasteboard generalPasteboard]];
  }
}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4240087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档