iOS網絡請求 添加全局代理 NSURLSessionConfiguration 解決方案


1、最近做項目、文件存儲服務器是用的亞馬遜的、如果直接訪問、下載其資源速度很慢、所以需要在網絡請求的時候添加一個代理、加速網絡訪問

2、代理服務器是一個HTTPS 的一個服務器

3、思路、解決方案、利用運行時機制(添加分類NSURLSession+Change)針對  NSURLSession 初始化添加代理對所有的網絡請求進行攔截處理

#import "NSURLSession+Change.h"

@implementation NSURLSession (Change)
+(void)load{
    Method oldMethod = class_getClassMethod(self, @selector(sessionWithConfiguration:delegate:delegateQueue:));
    Method newMethod = class_getClassMethod(self, @selector(newSessionWithConfiguration:delegate:NSURLSessiondelegateQueue:));
    
    Method oldMethod1 = class_getClassMethod(self, @selector(sessionWithConfiguration:));
    Method newMethod1 = class_getClassMethod(self, @selector(newSessionWithConfiguration:));
      
     method_exchangeImplementations(oldMethod1, newMethod1);
     method_exchangeImplementations(oldMethod, newMethod);
}
+ (NSURLSession *)newSessionWithConfiguration:(NSURLSessionConfiguration *)configuration{
    configuration=[self newConfiguration:configuration];
    NSURLSession *section=
       [self newSessionWithConfiguration:configuration];
       return section;
}
+ (NSURLSession *)newSessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate NSURLSessiondelegateQueue:(nullable NSOperationQueue *)queue{
    configuration=[self newConfiguration:configuration];
    NSURLSession *section=
    [self newSessionWithConfiguration:configuration delegate:delegate NSURLSessiondelegateQueue:queue];
    return section;
}
#pragma mark  添加代理,加速網絡請求
+(NSURLSessionConfiguration *)newConfiguration:(NSURLSessionConfiguration *)configuration{
//通過服務器配置HTTPS代理
    NSString *proxy=@"";
    NSInteger port=;
    configuration.connectionProxyDictionary = @{
          @"HTTPEnable":@YES,
          @"HTTPProxy":proxy,
          @"HTTPPort":@(port),
          @"HTTPSEnable":@YES,
          @"HTTPSProxy":proxy,
          @"HTTPSPort":@(port),
      };
    NSString *user=@"";
    NSString *password=@"";
    NSString* proxyIDPasswd = [NSString stringWithFormat:@"%@:%@",user,password];
    NSData* proxyoriginData = [proxyIDPasswd dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64EncodedCredential = [proxyoriginData base64EncodedStringWithOptions:0];
    NSString *authString = [NSString stringWithFormat:@"Basic: %@", base64EncodedCredential];
    configuration.HTTPAdditionalHeaders = @{@"Proxy-Authorization": authString};
    return configuration;
}
@end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM