ios 기반 AFN 패키징 네트워크 요청 도구

8831 단어
새 클래스

있다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;
            }
        }];
    }
    
    

    좋은 웹페이지 즐겨찾기