网络请求工具类的封装

使用的三方框架: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:^{
        
    }];
   
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,562评论 4 61
  • 最近的朋友圈被《人民的名义》刷爆了,作为每天的必修课,晚上新闻联播之后立马锁定湖南卫视收看最新的两级。我也加入了追...
    悟成阅读 4,442评论 1 49
  • 午觉醒来,全身酸痛,哦,是昨天跑步的后遗症,累,乏力,7月15日十点三十分,结束了急诊一周的见习,很无聊,很尴尬,...
    兔子要吃胡萝卜呀阅读 1,409评论 0 0
  • 桉术CRM:单纯将CRM作为销售跟踪工具的日子已经过去,CRM的未来是进行预测分析、加深对某一行业的理解、为工作流...
    桉术CRM阅读 3,759评论 0 5
  • 安静的地方总是远离闹市,美丽的风景总是路途遥远,但那些地方,那些风景往往最能触动心弦,让人欢喜。一直以来都...
    谁家的梅子阅读 3,434评论 0 4

友情链接更多精彩内容