美文网首页
AFNetworking简单封装

AFNetworking简单封装

作者: Hanser0503 | 来源:发表于2017-11-06 14:49 被阅读21次
    #import <Foundation/Foundation.h>
    
    typedef void(^HSSuccessBlock)(NSDictionary *data);
    typedef void(^HSFailureBlock)(NSError *error);
    
    @interface HTTPNetworkEngine : NSObject
    
    + (HTTPNetworkEngine *)shareInstantce;
    
    - (void)postWithUrl:(NSString *)url
              postParam:(NSDictionary *)postParam
                success:(HSSuccessBlock)success
                failure:(HSFailureBlock)failure;
    @end
    
    #import "HTTPNetworkEngine.h"
    #import "AFNetworking.h"
    
    static HTTPNetworkEngine *shareInstance = nil;
    const NSInteger outTime = 5;
    @implementation HTTPNetworkEngine
    
    + (HTTPNetworkEngine *)shareInstantce {
        static dispatch_once_t pred;
        dispatch_once(&pred, ^{
            shareInstance = [[self alloc] init];
        });
        return shareInstance;
    }
    
    - (void)postWithUrl:(NSString *)url
              postParam:(NSDictionary *)postParam
                success:(HSSuccessBlock)success
                failure:(HSFailureBlock)failure {
        AFHTTPSessionManager *mananger  = [AFHTTPSessionManager manager];
        /**可接收类型 */
        /**JSON */
        mananger.requestSerializer = [AFJSONRequestSerializer serializer];
        /**Dictionary */
        mananger.responseSerializer = [AFHTTPResponseSerializer serializer];
        mananger.operationQueue.maxConcurrentOperationCount = 10;
        mananger.requestSerializer.timeoutInterval = outTime;
        [mananger POST:url parameters:postParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                success(dic);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
                NSLog(@"网络异常");
            }
        }];
    }
    @end
    

    这里仅仅做一个post类型的封装,其他的以此类推。

    相关文章

      网友评论

          本文标题:AFNetworking简单封装

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