iOS OC封装AFN导致内存泄漏

 

解决:创建单例管理"AFHTTPSessionManager"

block封装AFN

.h文件

//
//  AFNRequest.h
//
//  Created by 周家稳 on 2018/5/7.
//  Copyright © 2018年 zhoujiawen. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "AFNetworking.h"
#import "RequestURL.h"



// 将系统现有类型定义一个类别
//************************第一步 声明block类型为字典类型用于输出字典数据
typedef void (^block) (NSDictionary *JsonData);

@interface AFNRequest : NSObject
//单例的构造
+(AFNRequest *)sharedManager;

//1.0 完整的链接POST
+(void)getDataForPOSTAndCompletedURL:(NSString *)KeyStr Verify:(BOOL)Verify Body:(NSDictionary *)bodyData Header:(NSDictionary *)header block:(block)block;
//1.1 完整的链接GET
+(void)getDataForGETAndCompletedURL:(NSString *)KeyStr Verify:(BOOL)Verify Body:(NSDictionary *)bodyData Header:(NSDictionary *)header block:(block)block;



@end

.m文件

//
//  AFNRequest.m
//
//  Created by 周家稳 on 2018/5/7.
//  Copyright © 2018年 zhoujiawen. All rights reserved.
//

#import "AFNRequest.h"

//    manager.requestSerializer = [AFJSONRequestSerializer serializer];//申明请求的数据是json类型
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];//申明返回的结果是json类型
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"]; // 设置content-Type为text/html

@implementation AFNRequest

static AFHTTPSessionManager *manager;
static AFURLSessionManager *urlsession ;

//单例的构造
+(AFNRequest *)sharedManager
{
    static AFNRequest *CTB_handle = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        CTB_handle = [[self alloc] init];
        [CTB_handle sharedHTTPSession];
        [CTB_handle sharedURLSession];
    });
    return CTB_handle;
}


//1.0 完整的链接POST
+(void)getDataForPOSTAndCompletedURL:(NSString *)KeyStr Verify:(BOOL)Verify Body:(NSDictionary *)bodyData Header:(NSDictionary *)header block:(block)block{
    NSString *url = KeyStr;
    if (Verify) {
        //加上这行代码,https ssl 验证。
        [manager setSecurityPolicy:[self customSecurityPolicy:url]];
    }else{
        AFSecurityPolicy * policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        policy.allowInvalidCertificates = YES;
        policy.validatesDomainName = NO;
        manager.securityPolicy = policy;
    }
    if (header) {
        for (NSString *headKey in header.allKeys) {
            [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[header objectForKey:headKey]] forHTTPHeaderField:headKey];
        }
    }
    NSDictionary *postDict = [NSDictionary dictionaryWithDictionary:bodyData];
    [manager POST:url parameters:postDict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        if ([responseObject objectForKey:@"err"]) {
            data[@"error"] = nil;
            data[@"err"] = [responseObject objectForKey:@"err"];
            data[@"status"] = @0;
        } else {
            data[@"data"] = responseObject;
            data[@"status"] = @1;
        }
        block(data);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        data[@"error"] = error;
        data[@"err"] = @"请求服务器出错";
        data[@"status"] = @0;
        block(data);
    }];
}
//1.1 完整的链接GET
+(void)getDataForGETAndCompletedURL:(NSString *)KeyStr Verify:(BOOL)Verify Body:(NSDictionary *)bodyData Header:(NSDictionary *)header block:(block)block{
    NSString *url = KeyStr;
    if (Verify) {
        //加上这行代码,https ssl 验证。
        [manager setSecurityPolicy:[self customSecurityPolicy:url]];
    }else{
        AFSecurityPolicy * policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        policy.allowInvalidCertificates = YES;
        policy.validatesDomainName = NO;
        manager.securityPolicy = policy;
    }
    if (header) {
        for (NSString *headKey in header.allKeys) {
            [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[header objectForKey:headKey]] forHTTPHeaderField:headKey];
        }
    }
    NSDictionary *postDict = [NSDictionary dictionaryWithDictionary:bodyData];
    [manager GET:url parameters:postDict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        if ([responseObject objectForKey:@"err"]) {
            data[@"error"] = nil;
            data[@"err"] = [responseObject objectForKey:@"err"];
            data[@"status"] = @0;
        } else {
            data[@"data"] = responseObject;
            data[@"status"] = @1;
        }
        block(data);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        data[@"error"] = error;
        data[@"err"] = @"请求服务器出错";
        data[@"status"] = @0;
        block(data);
    }];
}
 
 
 
//证书设置
+(AFSecurityPolicy*)customSecurityPolicy:(NSString *)url
{
    NSString *cerPath;
    if ([url hasPrefix:@"https://www.xxxx.com"]) {
        cerPath = [[NSBundle mainBundle] pathForResource:@"test1" ofType:@"cer"];//证书的路径
    }else if([url hasPrefix:@"https://www.xxxx.com"]){
        cerPath = [[NSBundle mainBundle] pathForResource:@"test2" ofType:@"cer"];//证书的路径
    }else if([url hasPrefix:@"https://www.xxxxxx.com"]){
        cerPath = [[NSBundle mainBundle] pathForResource:@"test3" ofType:@"cer"];//证书的路径
    }
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.pinnedCertificates = [NSSet setWithObjects:certData, nil];
    return securityPolicy;
}


-(AFHTTPSessionManager *)sharedHTTPSession{
    static dispatch_once_t onceTokenHTTP;
    dispatch_once(& onceTokenHTTP, ^{
        //manager = [AFHTTPSessionManager manager];
        manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:ZJWURL]];
        manager.requestSerializer.timeoutInterval = 10;
    });
    return manager;
}

-(AFURLSessionManager *)sharedURLSession{
    static dispatch_once_t onceTokenURL;
    dispatch_once(& onceTokenURL, ^{
        urlsession = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    });
    return urlsession;
}
   
//URL 转码

 NSString *urlString;
    if (@available(iOS 8.0, *)) {
        urlString = [[NSString stringWithFormat:@"%@%@",ZJWURL,MyUrl] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    }else{
        urlString = [[NSString stringWithFormat:@"%@",MyUrl] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }

 

展开阅读全文

没有更多推荐了,返回首页