ios 是否可以更改NSURLSessionConfiguration的defaultSessionConfiguration?

jobtbby3  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(93)

我有一个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];


在我的应用程序中有一个lib,它向某个主机发出请求。我知道这个lib使用NSURLSessionConfiguration defaultSessionConfiguration。我想修改“全局”defaultSessionConfiguration,以便lib开始通过我的代理发送请求。

iswrvxsc

iswrvxsc1#

您真正能做的唯一一件事就是混合该方法(我不能100%确定您不会遇到可能会阻止这样做的类集群异常)。
在高级别上,你会这样做:

  • 使用imp_implementationWithBlock . IIRC创建一个方法实现(IMP),其参数应该是:
  • 正在操作的对象
  • 方法参数按顺序
  • 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...
  });
}

字符串
以确保您不能重复此操作。
但是,请注意,在生产应用中这样做是相当危险的。最好尽可能要求框架开发人员提供钩子,以便传入您自己创建的会话(或您自己创建的配置)。
文档链接:

相关问题