美文网首页
ios基于AFN封装网络请求工具

ios基于AFN封装网络请求工具

作者: Arthur澪 | 来源:发表于2018-02-06 14:01 被阅读0次

    新建一个类

    在.h文件中,提供网络相关的常用方法

    GET请求

    +(void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure;
    

    POST请求

    +(void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure;
    

    PUT请求

    +(void)put:(NSString *)url params:(NSDictionary *)params success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure;
    

    网络状态监测

    +(void)getDeviceNetWorkStates;
    //+(UIAlertController *)showNetWorkStatusTipMesg:(NSString *)title ;
    

    处理参数得到请求URL

    +(NSString *)getURLwithParams:(NSString *)url secret:(NSString *)secret params:(NSMutableDictionary *)params;
    

    在.m文件中实现方法

    • GET
    
    + (void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
    {  
        AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
        [policy setAllowInvalidCertificates:YES];    //如果是需要验证自建证书,需要设置为YES
        
        policy.validatesDomainName = NO;//不验证证书的域名
        
        // 1.获得请求管理者
        AFHTTPSessionManager * mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
        
        mgr.requestSerializer.timeoutInterval = timeout;
       // mgr.operationQueue.maxConcurrentOperationCount = MaxOperationCountQueue;
        
        // 2.发送GET请求
        [mgr setSecurityPolicy:policy];
        mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
        mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //添加  请求头
        [mgr.requestSerializer setValue:@"abcd" forHTTPHeaderField:@"name"];
        
        [mgr GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
        {
            NSData *data = responseObject;
            id JSON =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (success) {
                success(JSON);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];  
    }
    
    • POST
    + (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
    {
        AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
        [policy setAllowInvalidCertificates:YES];
        // 1.获得请求管理者
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
        
        mgr.requestSerializer.timeoutInterval = timeout;
       // mgr.operationQueue.maxConcurrentOperationCount = MaxOperationCountQueue;
        
        [mgr setSecurityPolicy:policy];
        mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
        mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //添加  请求头
        [mgr.requestSerializer setValue:@"abcd" forHTTPHeaderField:@"name"];
        
        // 2.发送POST请求
        [mgr POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSData *data = responseObject;
            
            id JSON =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (success) {
                success(JSON);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
    }
    
    • PUT
    +(void)put:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
        AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
        [policy setAllowInvalidCertificates:YES];
        // 1.获得请求管理者
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
        
        mgr.requestSerializer.timeoutInterval = timeout;
        // mgr.operationQueue.maxConcurrentOperationCount = MaxOperationCountQueue;
        
        [mgr setSecurityPolicy:policy];
        mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
        mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        [mgr PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                success(responseObject);
            }
        }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
    }
    
    • 同步请求
    + (void)setAppleEnv{
        BOOL __block reqProcessed = NO;
        
        NSString *URLString = @"http://......."
        
        NSURLSession *session = [NSURLSession sharedSession];
        
        [[session dataTaskWithURL:[NSURL URLWithString:URLString]
                completionHandler:^(NSData *data,
                                    NSURLResponse *response,
                                    NSError *error) {
                    //接收
                    PDMessage *message = [PDMessage mj_objectWithKeyValues:data];
                    
                    if (message.code == 0) {
                        NSLog(@"----0 shenhe code=0");
                        
                    }else if ( message.code  == 1){
                        NSLog(@"----0 product code=1");
                    }
                    
                    reqProcessed = true;
                    
                }] resume];
        
        while (!reqProcessed) {
            [NSThread sleepForTimeInterval:0];
        }
    }
    
    • 参数排序,拼接,加密,获得URL
    +(NSString *)getURLwithParams:(NSString *)url secret:(NSString *)secret params:(NSMutableDictionary *)params{
        //排序
        NSArray * sortedKeys = [[params allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
        NSMutableString *sparam = [[NSMutableString alloc] init];
        for (int i = 0; i < sortedKeys.count; i++) {
            NSString *key = [sortedKeys objectAtIndex:i];
            NSString *value = [params objectForKey:key];
            if (i == 0) {
                [sparam appendFormat:@"%@=%@",key,value];
            }else{
                [sparam appendFormat:@"&%@=%@",key,value];
            }
        }
        if(secret != nil){
            //--加密工具方法
            PDEncryptionTools *enCoder = [[PDEncryptionTools alloc] init];
            NSString *sign = [enCoder getEncryption:sparam secret:secret];
            params[@"sign"] = sign; 
            //拼接
            [sparam appendFormat:@"&sign=%@",sign];
        }
        //请求地址
        NSString *requestURL = [NSString stringWithFormat:@"%@?%@",url,sparam];
    
        return requestURL;
    }
    
    • 网络状态监测
      使用通知发布状态信息
    +(void)getDeviceNetWorkStates{
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        [manager startMonitoring];
        
        [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            
            switch (status) {
                case AFNetworkReachabilityStatusReachableViaWWAN:
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",1]}];
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",1]}];
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",0]}];
                    break;
                case AFNetworkReachabilityStatusUnknown:
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",-1]}];
                    break;
                    
                default:
                    break;
            }
        }];
    }
    
    

    相关文章

      网友评论

          本文标题:ios基于AFN封装网络请求工具

          本文链接:https://www.haomeiwen.com/subject/smqgzxtx.html