[swift]-AFNetworking網絡封裝

1:定義一個網絡工具類,如HttpTools,NetworkTools等等html

在NetworkTools.swift類中:swift

這裏採用單例封裝:安全

import AFNetworking

// 枚舉方式1
enum RequestType {
    case GET
    case POST
}

// 枚舉方式2
enum RequestType1 : Int {
    case GET = 0
    case POST = 1
}

// 枚舉方式3
enum RequestType2 : String {
    case GET = "GET"
    case POST = "POST"
}



class NetworkTools: AFHTTPSessionManager {

    /// let是線程安全的
    static let shareInstance : NetworkTools = {
       let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
}

// MARK: - 封裝請求方法
extension NetworkTools {
    func request(methodType : RequestType, urlString : String, parameters : [String : AnyObject], finished:(result : AnyObject?,error : NSError?) -> ()) {
        
        // 定義成功的回調閉包:使用一個常量來接收它
        let successCallBack = { (task : NSURLSessionDataTask, result : AnyObject?) in
            finished(result: result, error: nil)
        }
        
        
        // 定義一個失敗的回調閉包:使用一個常量來接收它
        let failureCallBack = { (task : NSURLSessionDataTask?, error : NSError) in
            finished(result: nil, error: error)
        }
    
        // 發送網絡請求
        if methodType == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }else {
            POST(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
}

 

 

2:在viewController.swift中調用網絡請求接口網絡

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //print(NetworkTools.shareInstance)
        //print(NetworkTools.shareInstance)
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        /// 外面請求接口回調
        NetworkTools.shareInstance.request(.POST, urlString: "http://httpbin.org/post", parameters: ["name" : "lishengbing","age" : 106]) { (result, error) in
            if error != nil {
                print(error)
                return
            }
            
            print(result)
        }
    }
    

}

 

 

知識點:閉包

1:swift中建立單例:ide

class NetworkTools: AFHTTPSessionManager {

    /// let是線程安全的
    static let shareInstance : NetworkTools = {
       let tools = NetworkTools()
        return tools
    }()
}

2:swift中枚舉的定義:工具

// 枚舉方式1
enum RequestType {
    case GET
    case POST
}

// 枚舉方式2
enum RequestType1 : Int {
    case GET = 0
    case POST = 1
}

// 枚舉方式3
enum RequestType2 : String {
    case GET = "GET"
    case POST = "POST"
}

 

 

意見反饋郵件:1415429879@qq.com
歡迎大家的閱讀和讚揚、謝謝
post

相關文章
相關標籤/搜索