【问题标题】:UIPasteboard unable to copy text with expiration time multiple timesUIPasteboard 无法多次复制具有到期时间的文本
【发布时间】:2019-03-20 20:01:07
【问题描述】:

我在打电话:

UIPasteboard.general.setItems([[kUTTypePlainText as String: text]], options: [.localOnly: true, .expirationDate: expirationTime])

每次点击按钮复制文本。但是,在过期时间(30 秒)过后,复制功能将停止工作。在调试器中查看后,第二次(或之后)调用此行时,UIPasteboard 中的 items 数组返回为空。为什么会这样? Lastpass 等其他应用程序允许多次复制文本并设置过期时间。

我有一种预感,这可能与正在使用的密钥有关,有什么想法吗?

【问题讨论】:

    标签: ios swift clipboard uipasteboard pasteboard


    【解决方案1】:

    花了太多时间之后,我无法弄清楚为什么setItems(_:options:) 中的expirationDate 选项不适用于该功能的后续使用。没有关于此的任何其他文档。要么这是一个我无法弄清楚的基本琐碎问题,要么是 API 更复杂的问题。

    无论如何,我已经使用计时器实现了这个解决方案。这适用于所有 iOS 版本,我们只是在 30 秒后清除 UIPasteboard 的 items 数组。 expirationDate 选项仅适用于 iOS 10.3 及更高版本,而此功能更强大,适用于所有版本。

    class MyPasteboard {
        private static let shared = MyPasteboard()
        private let pasteboard = UIPasteboard.general
        private var expirationTimer: Timer?
    
        private init() {}
    
        static func copyText(_ text: String, expirationTime: TimeInterval = 30) {
            shared.pasteboard.string = text
            shared.expirationTimer?.invalidate()
            shared.expirationTimer = Timer.scheduledTimer(
                timeInterval: expirationTime,
                target: self,
                selector: #selector(expireText),
                userInfo: nil,
                repeats: false
            )
        }
    
        @objc private static func expireText() {
            shared.expirationTimer = nil
            shared.pasteboard.items = []
        }
    }
    

    有许多不同的方式来构建它,但我选择这样做是因为它允许我抽象出 UIPasteboard 复制功能并通过我需要的静态函数进行简单使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2015-03-03
      • 2012-09-18
      相关资源
      最近更新 更多