单例封装Alamofier网络请求

import Foundation
import Alamofire
class AlaRequestManager{
    
    // 请求单例
    static let shared:AlaRequestManager = {
        let m = AlaRequestManager()
        return m;
    }()
    
    func postRequest(urlString : String, params : [String : AnyObject], success : @escaping (_ responseObject : JSON)->(), failture : @escaping (_ error : NSError)->()) {
        
        Alamofire.request(urlString, method:.post, parameters: params).responseJSON
            {response in
               // print(response.result)
                if  response.result.isSuccess {
                    if let value = response.result.value{
                        success(JSON(value))
                    }
                }else{
                    let error = response.result.error
                    failture(error! as NSError)
                    
                }
        }
    }
}

封装之后的使用也非常简单,只需要调用,然后在闭包中填写数据的处理就可以了:
注意,我这里面Success闭包中返回的是JSON格式数据,使用的是SwiftyJson第三方,你也可以返回字典类型的数据自己解析。

            let params:[String:String] = {
                
                if self.titles.status![indexPath.row] == "1"{
                     return ["student_id":'' '']
            }()
            
            let url = rootURL
        
            AlaRequestManager.shared.postRequest(urlString: url, params: params as [String : AnyObject], success: ({
                js in
                print(js)           
            }), failture: ({
                error in          
                print(error)
                
            }))

你可能感兴趣的:(单例封装Alamofier网络请求)