Alamofire 和 URLSession 的一个对比例子
資深大佬 : Livid 40
https://medium.com/swift-programming/alamofire-vs-urlsession-a-comparison-for-networking-in-swift-c6cb3bc9f3b8
同样的一个需求,用 AF 实现:
AF.request("https://api.mywebserver.com/v1/board", method: .get, parameters: ["title": "New York Highlights"]) .validate(statusCode: 200..<300) .responseDecodable { (response: DataResponse) in switch response.result { case .success(let board): print("Created board title is (board.title)") // New York Highlights case .failure(let error): print("Board creation failed with error: (error.localizedDescription)") } }
用 URLSession 实现:
enum Error: Swift.Error { case requestFailed } // Build up the URL var components = URLComponents(string: "https://api.mywebserver.com/v1/board")! components.queryItems = ["title": "New York Highlights"].map { (key, value) in URLQueryItem(name: key, value: value) } // Generate and execute the request let request = try! URLRequest(url: components.url!, method: .get) URLSession.shared.dataTask(with: request) { (data, response, error) in do { guard let data = data, let response = response as? HTTPURLResponse, (200 ..< 300) ~= response.statusCode, error == nil else { // Data was nil, validation failed or an error occurred. throw error ?? Error.requestFailed } let board = try JSONDecoder().decode(Board.self, from: data) print("Created board title is (board.title)") // New York Highlights } catch { print("Board creation failed with error: (error.localizedDescription)") } }
大佬有話說 (0)