AFNetworking

初次学习OC简单封装AFNetworking,post请求

2016-03-23  本文已影响452人  Seizens_Swift

由于马上就要毕业了,但是在找工作之时,发现很多公司招iOS开发的斗士招oc程序员,而招swift的程序员基弧很少。所以不得不开始学习oc语法。
最近又在帮同学做项目,带着的小学弟是学oc的,所以也开始接触到一些oc的用法。
今天就涉及到AFNetworking的post请求。

1. 请求返回的协议

@protocol RequestDelegate <NSObject>

@optional

///请求成功
-(void) requestSuccess: (NSObject *)json :(NSString *) message;
///请求数据为空
-(void) requestDataNull: (NSString *)message;
/// 请求失败
-(void) requestFailure: (NSString *) message;

@end

2. 对AFNetworking进一步封装

+(void) getJson: (NSString *)url : (NSDictionary *)parpam : (id<RequestDelegate>) requestDelegate{

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parpam options:NSJSONWritingPrettyPrinted error:nil];

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *parameters = @{@"data":jsonString};

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSString *code = [responseObject valueForKey:@"code"];
        NSString *message = [responseObject valueForKey:@"message"];
        NSLog(@"1code:%@",code);
        NSLog(@"1message:%@",message);

        
        if ([code isEqualToString:@"E01"]) {
        
            [requestDelegate requestFailure:message];
        }
        
        else if ([code isEqualToString:@"N01"]){
            
            NSLog(@"code:%@",code);
        
            NSObject *content = [responseObject valueForKey:@"contents"];
            
            if (content) {
            
                [requestDelegate requestSuccess:content :message];
                
            }
            
            else {
            
                [requestDelegate requestDataNull:message];
            }
        }
        
            

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@", error);
        
        [requestDelegate requestFailure:@"错误"];
    }];

}
@end

3. 测试结果

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        NSString *urlString = @"http://121.43.112.141:8081/api/1.0/coach/coachinfo/changePassword";
        
        NSDictionary *param = @{@"coachPhone":@"12345678",@"coachPassword":@"123456"};
        
       
        [RequestUntils  getJson:urlString :param :self ];
        

        // Do any additional setup after loading the view, typically from a nib.
    }

    -(void)requestSuccess:(NSObject *)json :(NSString *)message {

        NSLog(@"1.%@",message);
    }

    -(void)requestDataNull:(NSString *)message{

        NSLog(@"2.%@",message);
    }

    -(void) requestFailure:(NSString *)message{

        NSLog(@"3.%@",message);
    }

总结,上面就是一个post请求的简单封装。源码在此

上一篇下一篇

猜你喜欢

热点阅读