12

我正在使用UIFeedback Haptic Enginewith swift 2.3,例如:

let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.Warning)

let generator = UIImpactFeedbackGenerator(style: .Heavy)
generator.impactOccurred()

今天我遇到了这样的新错误,找不到问题。你有什么主意吗?

UIFeedbackHapticEngine _deactivate] called more times than the feedback engine was activated

细节:

Fatal Exception: NSInternalInconsistencyException
0  CoreFoundation                 0x1863e41c0 __exceptionPreprocess
1  libobjc.A.dylib                0x184e1c55c objc_exception_throw
2  CoreFoundation                 0x1863e4094 +[NSException raise:format:]
3  Foundation                     0x186e6e82c -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:]
4  UIKit                          0x18cc43fb8 -[_UIFeedbackEngine _deactivate]
5  UIKit                          0x18cad781c -[UIFeedbackGenerator __deactivateWithStyle:]
4

3 回答 3

15

UIImpactFeedbackGenerator不是线程安全的,因此请确保您正在generator.impactOccurred()同步调用而不是在一个dispatch_async或另一个异步线程中。

于 2016-10-27T09:53:17.710 回答
6

通话将在iOS 11.*generator.impactOccurred()上崩溃。您需要在主线程上调用它。async

let generator = UIImpactFeedbackGenerator(style: style)
generator.prepare()

DispatchQueue.main.async {
   generator.impactOccurred()
}
于 2018-08-15T14:57:43.703 回答
1

只是为了完成已经给出的答案:您想要做的是要么有一个 OperationQueue 要么一个 DispatchQueue 将始终用于调用 FeedbackGenerator 的函数。请记住,对于您的用例,您可能必须释放生成器,但一个最小的示例是:

class HapticsService {

    private let hapticsQueue = DispatchQueue(label: "dev.alecrim.hapticQueue", qos: .userInteractive)

    typealias FeedbackType = UINotificationFeedbackGenerator.FeedbackType

    private let feedbackGeneator = UINotificationFeedbackGenerator()
    private let selectionGenerator = UISelectionFeedbackGenerator()

    func prepareForHaptic() {
        hapticsQueue.async {
            self.feedbackGeneator.prepare()
            self.selectionGenerator.prepare()
        }
    }

    func performHaptic(feedback: FeedbackType) {
        hapticsQueue.async {
            self.feedbackGeneator.notificationOccurred(feedback)
        }
    }

    func performSelectionHaptic() {
        hapticsQueue.async {
            self.selectionGenerator.selectionChanged()
        }
    }

}

这几乎解决了我们在生产中的相关崩溃。

于 2020-10-06T15:49:10.787 回答