Creating a generic method with AlamoFire in Swift

前端 未结 1 463
我寻月下人不归
我寻月下人不归 2021-01-06 08:59

I am using AlamoFire for my API calls, and have something like this all over my project:

static func login(userName: String, password: String) -> User {
          


        
相关标签:
1条回答
  • 2021-01-06 09:26

    you can use a BaseObject to do this easy :

    class BaseUser: ResponseObjectSerializable {
        var valueHandle : ((BaseUser)->())?
        var errorHandle : ((NSError)->())?
    
        required init?(response: NSHTTPURLResponse, representation: AnyObject) {
    
        }
    }
    
    
    
    func sendRequest<T:BaseUser>(method: Alamofire.Method, urlString: String, parameters: [String: AnyObject]?) -> T {
        let res : T
        Alamofire.request(method, urlString, parameters:parameters)
            .validate()
            .responseObject { (response: Response<T, NSError>) in
                switch response.result {
                case .Success(let value):
                    res.valueHandle?(value)
                case .Failure(let error):
                    res.errorHandle?(error)
                }
        }
    
        return res
    }
    

    class can hold the handle ,and with the baseobj you don't need to write them again and again by using protocol

    0 讨论(0)
提交回复
热议问题