iOS 网络工具类的封装(Swift和ObjectC)

Swift:

import UIKit

import AFNetworking(Alamofire没用过不敢用😀)
//建议继承自NSObject(更好的适配第三方库的改动,也就是江湖上盛传的对AFN的三层封装)
class KVNetworkTool: NSObject {
    
    let afnManager: AFHTTPSessionManager
    //实现网络单例(超简单实行单例,OC要写一大坨)
    static let sharedNetworkTool = KVNetworkTool()
    //自己实现构造函数
    override init() {
   //baseURL在项目中可以放心填(写全URL会自动替换)
        afnManager = AFHTTPSessionManager(baseURL: NSURL(string: "https://api.weibo.com/oauth2/"))
   //text/plain报的是什么格式的错就填加对应格式就行     
 afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    ///自定义的get请求
    func requestGET(URLString: String,parameters: AnyObject?,progress: ((NSProgress) -> Void)?,success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure:((NSURLSessionDataTask?, NSError) -> Void)?) {
        afnManager.GET(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
    }
    
    ///不带上传的post请求
    func requsetPOST(URLString: String, parameters: AnyObject?, progress: ((NSProgress) -> Void)?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) {
        afnManager.POST(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
    }
    
    ///上传的post请求
    func requsetPOST(URLString: String, parameters: AnyObject?, constructingBodyWithBlock: ((AFMultipartFormData) -> Void)?, progress: ((NSProgress) -> Void)?, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: ((NSURLSessionDataTask?, NSError) -> Void)?) {
        afnManager.POST(URLString, parameters: parameters, constructingBodyWithBlock: constructingBodyWithBlock, progress: progress, success: success, failure: failure)
    }
}

OC我就不写注释啰嗦啦见谅😀
ObjectC:
.h文件中

#import <Foundation/Foundation.h>
#import <AFNetworking.h>

@interface VZNetworkTool : NSObject

///网络请求管理者
+ (instancetype)sharedManager;
///POST网络请求不带参数
- (void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters completion:(void (^)(id json, NSError *error))completion;
///GET网络请求
- (void)GET:(NSString *)URLString parameters:(NSDictionary *)parameters completion:(void (^)(id json, NSError *error))completion;

///上传图片
-(void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>   formData))constructingBodyWithBlock completion:(void (^)(id json, NSError *error))completion;
@end

.m文件中

#import "VZNetworkTool.h"

@interface VZNetworkTool ()
///afn的网络请求管理者
@property(nonatomic,strong)AFHTTPSessionManager *afnNetworkManager;

@end

@implementation VZNetworkTool

///网络请求管理者
+ (instancetype)sharedManager {
    
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self.afnNetworkManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@""]];
    self.afnNetworkManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    
    return self;
}

- (void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters completion:(void (^)(id json, NSError *error))completion {

   [self.afnNetworkManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       completion(responseObject,nil);
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       completion(nil,error);
   }];
}

- (void)GET:(NSString *)URLString parameters:(NSDictionary *)parameters completion:(void (^)(id json, NSError *error))completion {
    
    [self.afnNetworkManager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        completion(responseObject, nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"网络请求失败 %@", error);
        
        completion(nil, error);
    }];
}

-(void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>   formData))constructingBodyWithBlock completion:(void (^)(id json, NSError *error))completion {
    
    [self.afnNetworkManager POST:urlString parameters:parameters constructingBodyWithBlock:constructingBodyWithBlock
 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completion(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(nil, error);
    }];
}
/*
 温馨提示:上传图片将图片转换成二进制
 NSData *imageData = UIImagePNGRepresentation(image);
 [formData appendPartWithFileData:imageData name:@"pic" fileName:@"smg" mimeType:@"image/png"];
 */
@end

我要不要脸啦!给我💕💖吧😀😀

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2015-12-19梁道丰白日梦想家 图片摘自网络 最近要把2013年出去晃悠了三个月的片段陆续的整理出来,重拾那...
    踏空萃取阅读 816评论 10 5
  • 江城,大风。春雨将至。 江止走到楼梯口,微探头看了看楼梯拐角处的玻璃窗户外。马上就要下大雨了吧,天气预报是这样说的...
    顾一声阅读 420评论 1 2
  • W是个疯疯癫癫看起来却又特立独行的小眼睛女孩,可认识她的人才会知道,她有多随意,或者说随心所欲。 与小眼睛男孩J的...
    小眼睛也很萌阅读 287评论 0 0