跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • Alamofire 和 URLSession 的一个对比例子
未分類
20 1 月 2022

Alamofire 和 URLSession 的一个对比例子

Alamofire 和 URLSession 的一个对比例子

資深大佬 : Livid 43

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)

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具