想问下大家是怎样封装Alamofire的

无敌鲨鱼炮
  • 448

每个网络请求一般都会具备URL、参数、请求头和get与post的选择。在OC中,我是这样封装的:

#import "AFHTTPSessionManager+Util.h"

@implementation AFHTTPSessionManager (Util)

/**
 网络请求封装

 @param type 请求类型
 @param urlStr URL
 @param parameters 参数
 @param success 与后台交互成功的回调
 @param failure 与后台交互失败的回调
 */
+ (void)requestWithType:(AFHTTPSessionManagerRequestType)type URLString:(NSString *)urlStr parameters:(id)parameters success:(void (^)(NSURLSessionDataTask * task, id responseObj))success failure:(void (^)(NSURLSessionDataTask * task, NSError * error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
    // 设置请求头
    [manager.requestSerializer setValue:[Management getUniqueDeviceID] forHTTPHeaderField:@"CLIENT"];
    if ([User sharedSingleton].token) {
        [manager.requestSerializer setValue:[User sharedSingleton].token forHTTPHeaderField:@"TOKEN"];
    }
    // 请求类型
    if (type == AFHTTPSessionManagerRequestTypeGet) {
        [manager GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(task,error);
        }];
    }else if(type == AFHTTPSessionManagerRequestTypePost){
        [manager POST:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(task,error);
        }];
    }
}

@end

在swift中,你们用Alamofire是怎样封装的?希望可以分享下。

回复
阅读 3.3k
1 个回答

首先,将 API 所有接口定义到一个单独文件中进行管理:

// API 接口定义
struct ConstAPI {
    
    static let kAPIBaseURL: String = ""
    
    //首页微游记
    static let kAPIHomeMoment: String = kAPIBaseURL + ""
    
    // 首页目的地
    static let kAPIHomeDestination: String = kAPIBaseURL + ""
    
    
}

然后,用单例模式实现 HTTP 请求工具:

class HTTPTool: NSObject {
    static let defult = HTTPTool()
    
    private override init() {
        // 单例模式,防止出现多个实例
    }
    
    func getRequestWithURL(path :String,parameter:[String: AnyObject]?, success: @escaping (_ result: [String: AnyObject]) -> Void ,failure: @escaping (_ error: Error) -> Void ) -> Void {
        Alamofire.request(path, method: .get, parameters: parameter, encoding: JSONEncoding.default).responseJSON { response in
            
            if response.error != nil {
                failure(response.error!)
                return;
            }
            
            
            if let JSON = response.result.value {
                success(JSON as! [String: AnyObject])
            }
            
            
            
            return
        }
    }
    
    func postRequestWithURL(path :String,parameter:[String: AnyObject]?, complection: @escaping (_ result: [String: AnyObject]) -> Void,failure: @escaping (_ error: Error) -> Void  ) -> Void {
        Alamofire.request(path, method: .post, parameters: parameter, encoding: JSONEncoding.default).responseJSON { response in
            
            if response.error != nil {
                failure(response.error!)
                return;
            }
            
            if let JSON = response.result.value {
                complection(JSON as! [String: AnyObject])
            }
            
            return
        }
    }
    
    
    // delete、put 请求自己添加
}

最后,拓展一些可能常用的接口,例如登录、退出、权限验证:

// 用户相关常用 HTTP 
extension HTTPTool {
    func doLogout(success: @escaping (_ result: [String: AnyObject]) -> Void , failure: @escaping (_ error: Error) -> Void ) {
        
    }
    
    func doLogin(success: @escaping (_ result: [String: AnyObject]) -> Void , failure: @escaping (_ error: Error) -> Void ) {
        
    }
    
    func authorizationCheck(success: @escaping (_ result: [String: AnyObject]) -> Void , failure: @escaping (_ error: Error) -> Void ) {
        
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏