AFNetWorking封装使用

// 需要使用到MBProgressHUD, TKAlert, AFNetworking 三个开源的第三方工具
//
//  NetworkingOperation.m
//  AFHttpLearn
//
//  Created by lance on 14-9-30.
//  Copyright (c) 2014年 Lance. All rights reserved.
// 网络请求操作基类,

#import "NetworkingOperation.h"
#import "AFHTTPRequestOperationManager.h"

@interface NetworkingOperation ()
{
    MethodType _methodType;
}

@end

@implementation NetworkingOperation

- (void)getData
{
    _methodType = GET;
    
    [self startRequest];
}

- (void)postData
{
    _methodType = POST;
    
    [self startRequest];
}

/**
 *  网络请求
 */
- (void)startRequest
{
    AFHTTPRequestOperationManager *operationManager = [Singleton shareInstance].operationManager;
    AFHTTPRequestOperation *operation = nil;
    /**
     *  get
     */
    
    __block NetworkingOperation *blockself = self;
    if (_methodType == GET) {
        operation = [operationManager GET:self.path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            blockself.completion(responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            blockself.completion([error description]);
        }];
    } else if (_methodType == POST) {
        /**
         *  post
         */
        // 有文件要上传
        if (self.files && [self.files count] > 0) {
            [operationManager POST:self.path parameters:self.params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                for (int i = 0; i < [self.files count]; i ++) {
                    id dic = [_files objectAtIndex:i];
                    [formData appendPartWithFileURL:[NSURL URLWithString:[dic objectForKey:@"path"]] name:@"name" error:nil];
                }
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [blockself requestComplete:operation];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [blockself requestComplete:operation];
            }];
        } else {
            operation = [operationManager POST:self.path parameters:self.params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [blockself requestComplete:operation];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [blockself requestComplete:operation];
            }];
        }
    }
    /**
     *  添加到请求队列
     */
//    [operationManager.operationQueue addOperation:operation];
}

/**
 *  请求完成,反悔结果处理
 *
 *  @param requestOperation 请求操作
 */
- (void)requestComplete:(AFHTTPRequestOperation *)requestOperation
{
    id result = requestOperation.responseObject;
    
    if (requestOperation.response.statusCode == 200 && result) {
        
    } else if (requestOperation.response.statusCode == 0) {
        
        NSString *errorDescription = [requestOperation.error.userInfo objectForKey:@"NSLocalizedDescription"];
        [self showMessage:errorDescription ? errorDescription : @"网络异常"];
    } else {
        [self showMessage:@"数据异常"];
    }
    
    if (self.completion) {
        self.completion(result);
    }
}

/**
 *  提示信息
 *
 *  @param message 
 */
- (void)showMessage:(NSString *)message
{
    [[TKAlertCenter defaultCenter] postAlertWithMessage:message];
}

@end

//
//  NetworkItemBase.h
//  AFHttpLearn
//
//  Created by lance on 14-9-30.
//  Copyright (c) 2014年 Lance. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NetworkingOperation.h"

@interface NetworkItemBase : NSObject
{
    /**
     *  主机地址
     */
    NSString *_host;
    /**
     *  访问路径
     */
    NSString *_path;
    /**
     *  请求参数
     */
    NSDictionary *_params;
    /**
     *  文件上传,数组中元素类型是一个字典,eg@[@{@"image":image, @"name":name}], image 是一个UIImage类型,name是一个NSString类型
     */
    NSArray *_files;
}

/**
 *  请求完成回调
 */
@property (nonatomic, strong) void (^completion) (id result, BOOL succ);
/**
 *  get 请求
 */
- (void)startGet;
/**
 *  post 请求
 */
- (void)startPost;
/**
 *  请求虚函数
 */
- (void)startRequest;

@end

//  网络请求 二次数据封装
//  NetworkItemBase.h
//  AFHttpLearn
//
//  Created by lance on 14-9-30.
//  Copyright (c) 2014年 Lance. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NetworkingOperation.h"

@interface NetworkItemBase : NSObject
{
    /**
     *  主机地址
     */
    NSString *_host;
    /**
     *  访问路径
     */
    NSString *_path;
    /**
     *  请求参数
     */
    NSDictionary *_params;
    /**
     *  文件上传,数组中元素类型是一个字典,eg@[@{@"image":image, @"name":name}], image 是一个UIImage类型,name是一个NSString类型
     */
    NSArray *_files;
}

/**
 *  请求完成回调
 */
@property (nonatomic, strong) void (^completion) (id result, BOOL succ);
/**
 *  get 请求
 */
- (void)startGet;
/**
 *  post 请求
 */
- (void)startPost;
/**
 *  请求虚函数
 */
- (void)startRequest;

@end

//
//  NetworkItemBase.m
//  AFHttpLearn
//
//  Created by lance on 14-9-30.
//  Copyright (c) 2014年 Lance. All rights reserved.
//

#import "NetworkItemBase.h"

@implementation NetworkItemBase

- (id)init
{
    self = [super init];
    if (self) {
        /**
         *  设置默认主机地址,eg: http://www.baidu.com
         */
        _host = kMainApiURL;
    }
    
    return self;
}

- (void)startGet
{
    [self sendRequest:GET];
}

- (void)startPost
{
    [self sendRequest:POST];
}

- (void)startRequest
{
    
}

/**
 *  请求结果完成
 *
 *  @param result 返回结果
 *  @param succ   是否成功
 */
- (void)requestComplete:(id)result succ:(BOOL)succ
{
    if (!succ) {
        
    }
    if (self.completion) {
        self.completion(result, succ);
    }
}

/**
 *  发送请求
 *
 *  @param methodType 请求类型 post or get
 */
- (void)sendRequest:(MethodType)methodType
{
    [[Singleton shareInstance] startLoading];
    
    NetworkingOperation *networkOperation = [[NetworkingOperation alloc] init];
    networkOperation.path = [NSString stringWithFormat:@"%@/%@",_host, _path];
    networkOperation.params = _params;
    /**
     *  判断是否有文件要上传
     */
    NSMutableArray *tempFiles = nil;
    if (_files && [_files count] > 0) {
        tempFiles = [NSMutableArray array];
        for (int i = 0; i < [_files count]; i ++) {
            NSDictionary *dic = [_files objectAtIndex:i];
            /**
             *  图片压缩
             */
            UIImage *image = [self scaleImage:[dic objectForKey:@"image"] toSize:CGSizeMake(800, 600)];
            
            NSData *data = nil;
            if (UIImagePNGRepresentation(image) == nil) {
                data = UIImageJPEGRepresentation(image, 0.6);
            } else {
                data = UIImagePNGRepresentation(image);
            }
            
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
            NSString *filePath = [cachePath stringByAppendingFormat:@"/upload-file-%i.jpg",i];
            
            NSFileManager *fileManager =  [NSFileManager defaultManager];
            [fileManager createFileAtPath:filePath contents:data attributes:nil];
            
            NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [newDic setObject:filePath forKey:@"path"];
            [tempFiles addObject:newDic];
        }
    }
    
    networkOperation.files = tempFiles;
    networkOperation.completion = ^(id result) {
        [self privateComplete:result];
    };
    
    if (methodType == POST) {
        [networkOperation postData];
    } else {
        [networkOperation getData];
    }
}

/**
 *  请求完成处理
 *
 *  @param result 返回结果
 */
- (void)privateComplete:(id)result
{
    [[Singleton shareInstance] stopLoading];
    
    BOOL flag = NO;
    if ([result isKindOfClass:[NSDictionary class]]) {
        /**
         *  处理返回的数据 根据后台接口反返回的return code来判断是否请求成功,失败,网络异常等信息
         */
        flag = YES;
    }
    [self requestComplete:result succ:flag];
}

/**
 *  图片压缩
 *
 *  @param image 原始图片
 *  @param size  压缩大小
 *
 *  @return 压缩后图片
 */
- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)size
{
    UIImage *newImage;
    
    int h = image.size.height;
    int w = image.size.width;
    
    /**
     *  不用缩放
     */
    if (h <= size.height && w <= size.width) {
        newImage = image;
    } else {
        float destWith = 0.0f;
        float destHeight = 0.0f;
        if (w > h) {
            destWith = (float)size.width;
            destHeight = size.width * (float) h / w;
        } else {
            destHeight = (float)size.height;
            destWith = size.height * (float) w / h;
        }
        
        CGSize itemSize = CGSizeMake(destWith, destHeight);
        UIGraphicsBeginImageContext(itemSize);
        CGRect imageRect = CGRectMake(0.0, 0.0, destWith, destHeight);
        [image drawInRect:imageRect];
        UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        newImage = newImg;
    }
    
    return newImage;
}

@end

//
//  Singleton.h
//  AFLearn
//
//  Created by lance on 14-9-30.
//  Copyright (c) 2014年 Lance. All rights reserved.
//

#import <Foundation/Foundation.h>

@class AFHTTPRequestOperationManager;
@class MBProgressHUD;

@interface Singleton : NSObject
{
    MBProgressHUD *_loadingView;
    NSUInteger _loadingCount;
}

@property (nonatomic, strong) AFHTTPRequestOperationManager *operationManager;

+ (instancetype)shareInstance;
/**
 *  网络请求打转
 */
- (void)startLoading;
- (void)stopLoading;
- (void)startLoadingInView:(UIView *)view;

@end

//
//  Singleton.m
//  AFLearn
//
//  Created by lance on 14-9-30.
//  Copyright (c) 2014年 Lance. All rights reserved.
//

#import "Singleton.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD.h"

@implementation Singleton

+ (instancetype)shareInstance
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc]  init];
    });
    
    return instance;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.operationManager = [[AFHTTPRequestOperationManager alloc] init];
    }
    
    return self;
}

- (void)startLoading
{
    [self startLoadingInView:[UIApplication sharedApplication].delegate.window];
}

- (void)stopLoading
{
    if (_loadingCount > 0) {
        _loadingCount --;
    }
    
    if (_loadingCount == 0) {
        [_loadingView hide:YES];
        [_loadingView removeFromSuperview];
        _loadingView = nil;
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }
}

- (void)startLoadingInView:(UIView *)view
{
    _loadingCount ++;
    if (_loadingCount == 1) {
        _loadingView = [[MBProgressHUD alloc] initWithView:view];
        _loadingView.labelText = @"正在加载中...";
        [_loadingView show:YES];
    } else {
        [_loadingView removeFromSuperview];
    }
    [view addSubview:_loadingView];
}

@end





猜你喜欢

转载自blog.csdn.net/lanliang901125/article/details/39930347
今日推荐