1、AFNetworking是IOS开发目前主流网络请求框架,目前最新发布的版本为3.0,对老版本用户可查看迁移指南,地址为:github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide
2、MJExtention是字典转模型框架,当然还有其他字典转模型框架,只是这个国内开发者用的比较多。地址为:github.com/CoderMJLee/MJExtension
直接上代码直观展示最基础的功能(这里没有进一步解耦代码,初学者很好理解)
这里是服务器返回的Json数据格式:
{
"meta": {
"message": "登录成功!",
"status_code": 200
},
"data": {
"token": "eyJ0eXAiOiiOiJIUzI1NiJ9.sIm5iZiI6MTzkifQ.piS_YZhOqsjAF4XbxELIs2y70cq8",
}
}
下面是模型的实现:
Login.h
#import <Foundation/Foundation.h>
@class Meta,Data;
@interface Login : NSObject
@property (nonatomic,strong) Meta* meta;
@property (nonatomic,strong) Data* data;
@end
@interface Meta : NSObject
@property (nonatomic,copy) NSString* message;
@property (nonatomic,assign) NSInteger status_code;
@end
@interface Data : NSObject
@property (nonatomic,copy) NSString* token;
@end
Login.m
#import "Login.h"
@implementation Login
@end
@implementation Meta
@end
@implementation Data
@end
这里简单发送一个POST请求
AFHTTPSessionManager* manager=[AFHTTPSessionManager manager];
// manager.responseSerializer= [AFJSONResponseSerializer serializer];
NSString* url=[NSString stringWithFormat:@"%@%@",HTTPS_PREFIX,USER_LOGIN];
NSDictionary* parameters=@{
@"account":_accountField.text,
@"password":_passwordField.text
};
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@",responseObject);
if (![responseObject isKindOfClass:[NSDictionary class]]) return;
Login* login = [Login mj_objectWithKeyValues:responseObject];
if (login.meta.status_code==SUCESS) {
[UserAccountTool saveToken:login.data.token];
[self dismissViewControllerAnimated:YES completion:nil];
[self presentViewController:[[MainTabBarController alloc] init] animated:NO completion:nil];
}else{
MBProgressHUD* hud = [Tools creatHUD];
hud.mode = MBProgressHUDModeCustomView;
hud.label.text = login.meta.message;
[hud hideAnimated:YES afterDelay:2];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
MBProgressHUD* hud = [Tools creatHUD];
hud.mode = MBProgressHUDModeCustomView;
hud.label.text = NetWork_Err;
[hud hideAnimated:YES afterDelay:2];
}];
怎么样简单吧,如果有点帮助,帮忙点个赞O(∩_∩)O谢谢!