1. 程式人生 > >AFNetworking配合Swift3.0請求資料

AFNetworking配合Swift3.0請求資料

首先用橋接或pods將AFNetworking匯入專案,在這不再贅述,然後建立一個單例NetWorkTools.swift

繼承:AFHTTPSessionManager

import UIKit
import AFNetworking

//列舉定義請求方式
enum HTTPRequestType {
    case GET
    case POST
}

class NetworkManager: AFHTTPSessionManager {

    //單例
    static let shared = NetworkManager()

    /// 封裝GET和POST 請求
/// /// - Parameters: /// - requestType: 請求方式 /// - urlString: urlString /// - parameters: 字典引數 /// - completion: 回撥 func request(requestType: HTTPRequestType, urlString: String, parameters: [String: AnyObject]?, completion: @escaping (AnyObject?) -> ()) { //成功回撥 let
success = { (task: URLSessionDataTask, json: Any)->() in completion(json as AnyObject?) } //失敗回撥 let failure = { (task: URLSessionDataTask?, error: Error) -> () in print("網路請求錯誤 \(error)") completion(nil) } if requestType == .GET { get
(urlString, parameters: parameters, progress: nil, success: success, failure: failure) } else { post(urlString, parameters: parameters, progress: nil, success: success, failure: failure) } } }

呼叫的地方

NetworkManager.shared.request(requestType: .GET, urlString: "https:www.baidu.com", parameters: ["userName": "zhangsan" as AnyObject]) { (json) in
    print(json)
}