博客> iOS AFNetworking封装的网络请求
iOS AFNetworking封装的网络请求
2017-12-12 14:07 评论:0 阅读:506 FBY展菲
ios 网络请求 AFNetworking

一: 封装的好处

1.1 可以降低网络请求方法与Controller(控制器)的耦合度,即使网络使用的第三方框架发生不兼容、错误等问题从而想换框架时,也不用到每个控制器里面改代码(50、60页面会改到想哭)。 1.2 建立独立的工具类,方便管理。 1.3 优化代码结构。

二:导入AFNetworking

导入AFNetworking有两种方法: 一种直接将AFNetworking文件拖入项目; 另一种使用CocoaPods导入。

三:创建封装类

创建FBYHomeService类继承NSObject .h代码

//
//  FBYHomeService.h
//  agreePay
//
//  Created by fbyon 2017/4/24.
//  Copyright © 2017年 agreePay. All rights reserved.
//

#import <Foundation>

@interface FBYHomeService : NSObject

//pageNum和action标记参数,可以区分接口类型等
//Alldic为网络请求报文
//url接口地址
//success获取接口成功返回参数
//failure网络请求失败错误信息
- (void)searchMessage:(NSString *)pageNum andWithAction:(NSString *)action andWithDic:(NSDictionary *)Alldic andUrl:(NSString *)url andSuccess:(void(^)(NSDictionary *dic))success andFailure:(void(^)(int fail))failure;

@end

.m代码

//
//  FBYHomeService.m
//  agreePay
//
//  Created by 范保莹 on 2017/4/24.
//  Copyright © 2017年 agreePay. All rights reserved.
//

#import "FBYHomeService.h"

#import "AFNetworking.h"

@implementation FBYHomeService
- (void)searchMessage:(NSString *)pageNum andWithAction:(NSString *)action andWithDic:(NSDictionary *)Alldic andUrl:(NSString *)url andSuccess:(void (^)(NSDictionary *))success andFailure:(void (^)(int))failure{

    //1.创建ADHTTPSESSIONMANGER对象
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    //2.设置该对象返回类型
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

if ([pageNum isEqualToString:[NSString stringWithFormat:@"get"]]) {

        NSString *urlstr= [NSString stringWithFormat:@"%@%@",AGREEHanBingURL,url];

        NSLog(@"%@",urlstr);
        //调出请求头
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //将token封装入请求头

        NSUserDefaults *tokenid = [NSUserDefaults standardUserDefaults];
        NSString *token = [tokenid objectForKey:@"tokenid"];
        NSLog(@"%@",token);

        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];

        [manager GET:urlstr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = responseObject;
            success(dic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        }];

    }else {
            NSString *urlstr= [NSString stringWithFormat:@"%@%@",AGREENewFuWuURL,url];
            NSLog(@"%@",urlstr);
            [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"x-signature"];
            [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"x-timestamp"];
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            [manager POST:urlstr parameters:Alldic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

                  NSDictionary *dic = responseObject;

                  success(dic);

              }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  failure(404);
              }];   
    }
}

@end

四:封装类的使用

LoginViewController.m中代码 首先引入头文件

#import "AFNetworking.h"
#import "FBYHomeService.h"

使用代码

NSMutableDictionary *mutdic=[NSMutableDictionary dictionaryWithCapacity:0];

    mutdic[@"userName"] = @"admin";
    mutdic[@"password"] = @"admin";

    //网络请求
    FBYHomeService *service1 = [[FBYHomeService alloc]init];

    [service1 searchMessage:@"post" andWithAction:nil andWithDic:mutdic andUrl:MerchantLogin andSuccess:^(NSDictionary *dic) {

        NSLog(@"%@",dic);

        NSString *str = [dic objectForKey:@"code"];
        int intString = [str intValue];

        if (intString == 0) {

            NSString *token = [dic objectForKey:@"token"];

            NSLog(@"%@",token);
            NSUserDefaults *tokenid = [NSUserDefaults standardUserDefaults];
            [tokenid setObject:token forKey:@"tokenid"];
            [tokenid synchronize];

        }else{

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[dic objectForKey:@"msg"] preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            }];
            [alert addAction:action1];
            [self presentViewController:alert animated:YES completion:nil];

        }

    } andFailure:^(int fail) {

    }];
收藏
0
sina weixin mail 回到顶部