提问人:Shmulinson 提问时间:10/20/2023 最后编辑:Shmulinson 更新时间:11/14/2023 访问量:35
是否可以更改 NSURLSessionConfiguration 的 defaultSessionConfiguration?
Is it possible to change defaultSessionConfiguration of NSURLSessionConfiguration?
问:
我有一个ios应用程序。我想修改,以便每次以后在代码中调用时,我都会得到修改defaultSessionConfiguration
[NSURLSessionConfiguration defaultSessionConfiguration]
defaultSessionConfiguration
我尝试过这样的事情,但没有用
NSURLSessionConfiguration *configuration = NSURLSessionConfiguration.defaultSessionConfiguration;
// Set the proxy configuration options in the connectionProxyDictionary property
NSDictionary *proxyDict = @{
@"HTTPSEnable": [NSNumber numberWithInt:1],
@"HTTPSProxy": @"localhost",
@"HTTPSPort": [NSNumber numberWithInt:1234]
};
configuration.connectionProxyDictionary = proxyDict;
这个给了我一个空的 connectionProxyDictionary 配置
NSURLSessionConfiguration *configuration2 = [NSURLSessionConfiguration defaultSessionConfiguration];
我的应用程序中有一个库可以向某个主机发出请求。我知道这个库使用 .我想修改“全局”,以便库开始通过我的代理发送请求。NSURLSessionConfiguration defaultSessionConfiguration
defaultSessionConfiguration
答:
0赞
dgatwood
11/14/2023
#1
你唯一能做的就是修改这个方法(我不能 100% 确定你不会遇到可能阻止这样做的类集群怪异)。
在较高级别上,你会做这样的事情:
- 使用 创建方法实现 ()。IIRC,其参数应为:
IMP
imp_implementationWithBlock
- 正在操作的对象
- 方法参数顺序
- 使用 查找方法。
class_getInstanceMethod
- 使用 替换该方法的实现。
method_setImplementation
- 将该方法的结果(上一个)存储在静态全局变量中。
IMP
- 将 IMP 转换为函数指针。IIRC,函数指针的参数应该是:
- 正在操作的对象
- 方法的选择器 (
@selector(defaultSessionConfiguration)
) - 方法参数顺序
- 从自定义实现块调用该函数指针,然后在返回结果之前修改结果。
确保在dispatch_once块中完成所有这些操作,例如
- (void)load {
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
// Code goes here...
});
}
以确保您不能多次执行此操作。
但请注意,在生产应用中这样做是相当危险的。最好尽可能要求框架开发人员提供钩子,以便传入您自己创建的会话(或您自己创建的配置)。
文档链接:
评论
defaultSessionConfiguration