How to access iOS private APIs in Swift?

荒凉一梦 提交于 2019-11-28 09:09:59

You can do the very same trick that you would do if your project was in Objective-C.

Create a header file and put the declaration of a category on the class, along with the declaration of the private methods you wish to expose. Then, tell the Swift compiler to import this bridging header.

For demonstration purposes, I'm going to poke around in the internals of NSBigMutableString, a private subclass of NSMutableString, and I will call its _isMarkedAsImmutable method.

Note that here, the entire class itself is private, hence I have to declare it as a subclass of its real superclass first. Because of this, I could have as well declared the method right in the declaration of the class itself; that, however, wouldn't have demonstrated the usage of the (Private) trick-category.

If your class is public, then obviously you will only need the category, and you won't need to (re-)declare the class itself.

Bridge.h:

#import <Foundation/Foundation.h>

@interface NSMutableString (Private)
- (BOOL)_isMarkedAsImmutable; // this is a lie
@end

@interface NSBigMutableString : NSMutableString
@end

s.swift:

let s = NSBigMutableString()
println(s._isMarkedAsImmutable())

Compile and run:

$ xcrun -sdk macosx swiftc -o foo -import-objc-header Bridge.h s.swift
$ ./foo
false
$

You can get private classes using NSClassFromString: and interact with them using performSelector.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!