Access Private UIKit Function Without Using Bridging Header

人盡茶涼 提交于 2019-11-28 19:44:39

It's a lot easier than you would expect:

@asmname("_UICreateScreenUIImage")
func _UICreateScreenUIImage() -> UIImage

// That's it – go ahead and call it:
_UICreateScreenUIImage()

As it happens, @asmname has actually just been changed in the 2.3 builds to @_silgen_name, so be ready to adjust accordingly:

@_silgen_name("_UICreateScreenUIImage")
func _UICreateScreenUIImage() -> UIImage

To my knowledge, @_silgen_name does not provide resolution of Objective-C methods. For this, there is the evenmore powerful Objective-C runtime API:

let invokeImageNamed: (String, NSTimeInterval) -> UIImage? = {
    // The Objective-C selector for the method.
    let selector: Selector = "animatedImageNamed:duration:"
    guard case let method = class_getClassMethod(UIImage.self, selector)
        where method != nil else { fatalError("Failed to look up \(selector)") }

    // Recreation of the method's implementation function.
    typealias Prototype = @convention(c) (AnyClass, Selector, NSString, NSTimeInterval) -> UIImage?
    let opaqueIMP = method_getImplementation(method)
    let function = unsafeBitCast(opaqueIMP, Prototype.self)

    // Capture the implemenation data in a closure that can be invoked at any time.
    return { name, interval in function(UIImage.self, selector, name, interval) }
}()

extension UIImage {
    // Convenience method for calling the closure from the class.
    class func imageNamed(name: String, interval: NSTimeInterval) -> UIImage? {
        return invokeImageNamed(name, interval)
    }
}

UIImage.imageNamed("test", interval: 0)

As far as handling NS_RETURNS_RETAINED, this won't be generated for you. Instead, you can use a return type of Unmanaged, and wrap that in a function to your convenience:

@_silgen_name("_UICreateScreenUIImage")
func _UICreateScreenUIImage() -> Unmanaged<UIImage>
func UICreateScreenUIImage() -> UIImage {
    return _UICreateScreenUIImage().takeRetainedValue()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!