Created
June 16, 2021 11:46
-
-
Save SandeepAggarwal/a0ee7ed3c67921a4e62b5d344378a783 to your computer and use it in GitHub Desktop.
Swizzling demo implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///copy the implementation of NSObject.init and exchange it with some new fake init we are going to create. | |
///https://nshint.io/blog/2019/04/08/testing-the-camera-on-the-simulator/ | |
///https://pspdfkit.com/blog/2019/swizzling-in-swift/ | |
private struct Swizzler { | |
private let klass: AnyClass | |
init(_ klass: AnyClass) { | |
self.klass = klass | |
} | |
func injectNSObjectInit(into selector: Selector) { | |
guard let original = class_getInstanceMethod(klass, selector), | |
let swizzled = class_getInstanceMethod(klass, #selector(NSObject.init)) else { | |
return | |
} | |
let types = method_getTypeEncoding(original) | |
let newImp = method_getImplementation(swizzled) | |
class_replaceMethod(klass, selector, newImp, types) | |
} | |
} | |
final class FakeMachineReadableCodeObject: AVMetadataMachineReadableCodeObject { | |
var code: String? | |
var dataType: AVMetadataObject.ObjectType = .qr | |
override var stringValue: String? { | |
code | |
} | |
override var type: AVMetadataObject.ObjectType { | |
dataType | |
} | |
@objc dynamic private convenience init(fake: String?) { | |
fatalError() | |
} | |
private class func fake(fake: String?, type: AVMetadataObject.ObjectType = .qr) -> FakeMachineReadableCodeObject { | |
let m = FakeMachineReadableCodeObject(fake: fake) | |
m.code = fake | |
m.dataType = type | |
return m | |
} | |
static func createFake(code: String?, type: AVMetadataObject.ObjectType) -> FakeMachineReadableCodeObject { | |
//we need to swizzle the implementation of this class's init with NSObject init because AVMetadataMachineReadableCodeObject | |
//is not intializable directly and it gets its values/gets intialize at runtime only | |
Swizzler(self).injectNSObjectInit(into: #selector(FakeMachineReadableCodeObject.init(fake:))) | |
return fake(fake: code, type: type) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment