4

iOS アプリ (ポッド) のフレームワークを開発しています。スウィズルしたい

application(_:didReceiveRemoteNotification:fetchCompletionHandler:)

私のフレームワークで定義されたメソッドで。これは私のコードです:

class MyClass {
    @objc
    func myCustomizedMethod(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // my code
    }

    private func swizzleDidReceiveRemoteNotification() {
        guard let appDelegateClass = object_getClass(UIApplication.shared.delegate) else { return }

        let originalSelector = #selector((appDelegateClass as! UIApplicationDelegate).application(_:didReceiveRemoteNotification:fetchCompletionHandler:))
        let swizzledSelector = #selector(MyClass.self.myCustomizedMethod(_:didReceiveRemoteNotification:fetchCompletionHandler:))

        guard let originalMethod = class_getInstanceMethod(appDelegateClass, originalSelector) else { return }
        guard let swizzledMethod = class_getInstanceMethod(MyClass.self, swizzledSelector) else { return }

        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
}

しかし、コードを実行すると、originalMethod の値が nil のように見えるので、

class_getInstanceMethod(appDelegateClass, originalSelector)

nil を返します。私が間違っていることは何ですか?(私が言ったように、私はフレームワークを開発しているので、私は AppDelegate にアクセスできないことを考慮してください)

4

2 に答える 2

4

これは私のために働いたコードです:

class MyClass {
    @objc
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // my code
    }

    private func swizzleDidReceiveRemoteNotification() {
        let appDelegate = UIApplication.shared.delegate
        let appDelegateClass = object_getClass(appDelegate)

        let originalSelector = #selector(UIApplicationDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:))
        let swizzledSelector = #selector(MyClass.self.application(_:didReceiveRemoteNotification:fetchCompletionHandler:))

        guard let swizzledMethod = class_getInstanceMethod(MyClass.self, swizzledSelector) else {
            return
        }

        if let originalMethod = class_getInstanceMethod(appDelegateClass, originalSelector)  {
            // exchange implementation
            method_exchangeImplementations(originalMethod, swizzledMethod)
        } else {
            // add implementation
            class_addMethod(appDelegateClass, swizzledSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
        }
    }
}
于 2019-09-15T07:29:01.483 に答える