美文网首页
网络请求工具类的封装

网络请求工具类的封装

作者: 搬码小能手 | 来源:发表于2017-08-29 17:04 被阅读285次

    使用的三方框架:pod 'AFNetworking', '~> 3.0'
    继承AFHTTPSessionManager的类
    官方注释:(英文很重要!!!)

    ## Subclassing Notes
    
     Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
    
     For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
    

    h文件

    //  Created by Mac on 2017/8/29.
    //  Copyright © 2017年 Mac. All rights reserved.
    //
    
    #import <AFNetworking/AFNetworking.h>
    
    @interface WJNetworkTools : AFHTTPSessionManager
    + (instancetype)sharedManager;
    @end
    
    

    m文件

    //  Created by Mac on 2017/8/29.
    //  Copyright © 2017年 Mac. All rights reserved.
    //
    
    #import "WJNetworkTools.h"
    
    @implementation WJNetworkTools
    + (instancetype)sharedManager{
        
        static id instance = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            NSURL * baseURL = [NSURL URLWithString:@"https://abcdefg1234567/index/"];
            NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
            //配置超时时长
            config.timeoutIntervalForRequest = 15;
            instance = [[self alloc]initWithBaseURL: baseURL sessionConfiguration:config];
        });
        return instance;
    }
    
    @end
    
    

    JSON数据结构:


    Jietu20170829-171833.png

    创建数据模型:
    h文件

    //  Created by Mac on 2017/8/29.
    //  Copyright © 2017年 Mac. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    @interface WJModel : NSObject
    @property (nonatomic,copy)NSString * title;
    @property (nonatomic,copy)NSString * describe;
    
    + (instancetype)wangjieWithDic:(NSDictionary *)dic;
    //发送异步请求,获取数据,字典转模型
    + (void)wangjie:(void(^)(NSArray * array))success error:(void(^)())error;
    
    
    @end
    
    

    m文件

    //  Created by Mac on 2017/8/29.
    //  Copyright © 2017年 Mac. All rights reserved.
    //
    
    #import "WJModel.h"
    #import "WJNetworkTools.h"
    @implementation WJModel
    
    + (instancetype)wangjieWithDic:(NSDictionary *)dic{
        WJModel * model = [self new];
        [model setValuesForKeysWithDictionary:dic];
        return model;
    }
    
    
    //防止请求到的字段多于你定义的字段
    - (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
    }
    
    
    //发送异步请求,获取数据,字典转模型
    + (void)wangjie:(void(^)(NSArray * array))success error:(void(^)())error{
    
        [[WJNetworkTools sharedManager] GET:@"new_list.php?os=0&index=news&limit=1&token=4f09ef8d44138f3c5e4b215a783d47dd" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  responseObject) {
            NSLog(@"请求成功");
            //获取返回的数组
            //获取字典的第一个键
            //NSString * rootKey = responseObject.keyEnumerator.nextObject;
            NSArray * array = responseObject[@"data"];
            //字典转模型
            NSMutableArray * mArray = [NSMutableArray arrayWithCapacity:4];
            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                WJModel * model = [self wangjieWithDic:obj];
                [mArray addObject:model];
            }];
            
            if (success) {
                success(mArray.copy);
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull err) {
            
            NSLog(@"请求失败%@",error);
            if (error) {
                error();
            }
        }];
    }
    
    
    //重写系统description(有的重写系统方法需要 super ,有的不需要,系统默认super要super,没有super的就不super)
    -(NSString *)description{
        return [NSString stringWithFormat:@"%@{name:%@,age:%@}",[super description],self.title,self.describe];
    }
    
    

    ViewController调用

    //  Created by Mac on 2017/8/29.
    //  Copyright © 2017年 Mac. All rights reserved.
    //
    
    #import "ViewController.h"
    #import "WJModel.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
    
        [WJModel wangjie:^(NSArray *array) {
            NSLog(@"array--%@",array);
        } error:^{
            
        }];
       
    }
    
    

    相关文章

      网友评论

          本文标题:网络请求工具类的封装

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