美文网首页
网络请求封装(基于AFNetworking)

网络请求封装(基于AFNetworking)

作者: 精神薇 | 来源:发表于2018-10-12 15:13 被阅读0次

    demo

    +(PJHttpTool *) defaultHttpTool{
        static PJHttpTool * s_Tool = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            s_Tool = [[PJHttpTool alloc]init];
        });
        return s_Tool;
    }
    -(AFHTTPSessionManager *)sessionManager{
        if (_sessionManager == nil) {
            _sessionManager = [PJHttpTool createSessionManagerWithUrl:RBDom];
        }
        return _sessionManager;
    }
    +(AFHTTPSessionManager *)createSessionManagerWithUrl:(NSString *)url
    {
        
        AFHTTPSessionManager * sessionManager = [AFHTTPSessionManager manager];
        sessionManager.requestSerializer.timeoutInterval = 10;
        
        
        
        //validatesDomainName 是否需要验证域名,默认为YES;
        sessionManager.securityPolicy.validatesDomainName =NO;
        sessionManager.securityPolicy.allowInvalidCertificates = YES;
        sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
        
        
        
        return sessionManager;
        
    }
    
    
    
    +(void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
    {
        
        //    UInt64 recordTime =  [NSDate date].timeIntervalSince1970*1000;
        //    NSNumber * intervalNow =[NSNumber numberWithUnsignedInteger:recordTime];
        //    NSLog(@"---%@--%@------",url,[NSNumber numberWithUnsignedInteger:recordTime]);
        NSMutableDictionary *paramsDic = [NSMutableDictionary dictionaryWithDictionary:params];
        
        //加入版本
        //    [paramsDic setObject:@"ios" forKey:@"appType"];
        //
        //    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        //    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
        //    app_build = [app_build substringFromIndex:2];
        //    [paramsDic setObject:app_build forKey:@"appVersion"];
        //    NSLog(@"%@",app_build);
        //    if ([[paramsDic objectForKey:@"token"] length]>0) {
        //        NSString * token = [NSString stringWithFormat:@"%@%@",intervalNow,[paramsDic objectForKey:@"token"]];
        //        NSString * aesStr = [SecurityUtil encryptAESData:token];
        //        [paramsDic setObject:aesStr forKey:@"token"];
        //    }
        
        AFHTTPSessionManager * sessionManager = [[PJHttpTool defaultHttpTool] sessionManager];
        [sessionManager POST:url parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSError * error = nil;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
                responseObject = jsonObject;
            }
            if ( [[responseObject objectForKey:@"successFlag"] integerValue] == -1) {
                [NeuProgressHUD hideHUDForView:nil];
                [NeuProgressHUD showError:HttpFail toView:nil];
                return ;
            }
            if (success)
            {
                if ([responseObject objectForKey:@"content"]) {
                    success([responseObject objectForKey:@"content"]);
                }else{
                    success(responseObject);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            [NeuProgressHUD hideHUDForView:nil];
            [NeuProgressHUD showError:HttpFail toView:nil];
            failure(error);
        }];
        
    }
    + (void)postWithLoading:(NSString *)url params:(NSDictionary *)params success:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure{
        [NeuProgressHUD showMessage:kLoadingBestAlertText toView:nil];
        [self post:url params:params success:^(id responseObj) {
            [NeuProgressHUD hideHUDForView:nil];
            if (success) {
                success(responseObj);
            }
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    }
    
    
    #pragma mark 上传视频数据
    +(void)uploadVideoWithUrl:(NSString *)url params:(NSDictionary *)params videoURL:(NSURL *)videourl progress:(void (^)(NSProgress * uploadProgress))progress success:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure{
        NSData *videoData = [NSData dataWithContentsOfURL:videourl];
        NSString *fileName = [videourl.absoluteString lastPathComponent];
        AFHTTPSessionManager * sessionManager = [[PJHttpTool defaultHttpTool] sessionManager];
        [sessionManager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:videoData name:@"uploadFile" fileName:fileName mimeType:@"video/mp4"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            progress(uploadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSError * error = nil;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
                responseObject = jsonObject;
            }
            if ( [[responseObject objectForKey:@"successFlag"] integerValue] == -1) {
                [NeuProgressHUD hideHUDForView:nil];
                [NeuProgressHUD showError:HttpFail toView:nil];
                return ;
            }
            if (success)
            {
                if ([responseObject objectForKey:@"content"]) {
                    success([responseObject objectForKey:@"content"]);
                }else{
                    success(responseObject);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [NeuProgressHUD hideHUDForView:nil];
           [NeuProgressHUD showError:HttpFail toView:nil];
           failure(error);
        }];
        
    
    }
    

    相关文章

      网友评论

          本文标题:网络请求封装(基于AFNetworking)

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