访问 Web 服务
使用 Swift 进行 iOS 开发 - 访问 Web 服务
Section titled “使用 Swift 进行 iOS 开发 - 访问 Web 服务”许多现代应用程序需要连接到 Web 服务(Web services)或 API(应用程序接口)来获取或发送数据。这可能用于检索天气信息、用户数据、新闻文章或与后端系统交互。Swift 主要通过 URLSession API 提供了强大的网络通信工具。我们还将简要介绍一个流行的第三方网络库 Alamofire。
使用 URLSession 进行基本网络请求
Section titled “使用 URLSession 进行基本网络请求”首先,你需要 Web 服务的 URL。例如,像 OpenWeatherMap 这样的公共 API 可能提供一个如下所示的 URL:
// 示例 URL(如有需要,请替换为有效 URL 和你的 API 密钥)// https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY关于 App Transport Security (ATS) 的重要说明:默认情况下,iOS 应用要求连接到 Web 服务必须使用 HTTPS(安全连接)。如果在开发期间或出于特定原因需要连接到 HTTP(非安全)服务,则必须在应用的 Info.plist 文件中添加例外。添加 App Transport Security Settings 字典,并在其中将 Allow Arbitrary Loads 设置为 YES。然而,对于生产应用,强烈建议使用 HTTPS。
使用 URLSession 发起网络请求:
import UIKit
// ... 在 ViewController 或其他类内部
func fetchData() { guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { print("Invalid URL") return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in // 检查错误 if let error = error { print("Error fetching data: \(error.localizedDescription)") return }
// 检查有效响应(例如:HTTP 200 OK) guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("Invalid response or status code") // 你可以在这里检查 httpResponse.statusCode return }
// 检查数据是否存在 guard let data = data else { print("No data received") return }
// 处理数据(例如:解析 JSON) do { // 示例:尝试将数据转换为 String 进行简单显示 if let dataString = String(data: data, encoding: .utf8) { print("Received data as String: \(dataString)") }
// 对于 JSON,你通常会使用 Codable 将其解码为 Swift struct/class // struct Todo: Codable { let userId: Int; let id: Int; let title: String; let completed: Bool } // let todoItem = try JSONDecoder().decode(Todo.self, from: data) // print("Decoded Todo item title: \(todoItem.title)")
// 如果需要,记住将 UI 更新分派到主线程 // DispatchQueue.main.async { // self.myLabel.text = todoItem.title // }
} catch { print("Error processing data: \(error.localizedDescription)") } }
// 启动任务 task.resume()}这个例子展示了获取数据、基本的错误检查以及处理接收到数据(通常是 JSON)的占位符。为了进行健壮的 JSON 解析,请使用 Swift 的 Codable 协议。
使用 async/await 与 URLSession(现代 Swift)
Section titled “使用 async/await 与 URLSession(现代 Swift)”Swift 的现代并发特性(async/await)可以简化异步网络请求:
@available(iOS 13.0, *)func fetchDataAsync() async { guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { print("Invalid URL") return }
do { let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("Invalid response or status code") return }
// 处理数据(例如:使用 Codable) // struct Todo: Codable { /* ... */ } // let todoItem = try JSONDecoder().decode(Todo.self, from: data) // print("Fetched (async) Todo item title: \(todoItem.title)")
// 示例:以字符串形式打印 if let dataString = String(data: data, encoding: .utf8) { print("Received data (async) as String: \(dataString)") }
// UI 更新必须在主 actor 上进行 // Task { @MainActor in // self.myLabel.text = todoItem.title // }
} catch { print("Error fetching or processing data (async): \(error.localizedDescription)") }}使用 async/await 使异步代码看起来更像同步代码,提高了可读性。
Alamofire(第三方库)
Section titled “Alamofire(第三方库)”Alamofire 是一个流行的 Swift HTTP 网络库,它为常见的网络任务提供了更流畅的 API。它处理了许多复杂性,例如参数编码、响应验证和多部分表单数据上传。
要使用 Alamofire,你需要先将其添加到项目中,通常使用依赖项管理器(dependency manager),如 Swift Package Manager (SPM) 或 CocoaPods。有关安装说明,请参阅 GitHub 上的 Alamofire 官方文档 (https://github.com/Alamofire/Alamofire)。
使用 Alamofire 发起请求
Section titled “使用 Alamofire 发起请求”安装完成后,你可以这样发起请求(语法可能随 Alamofire 版本略有不同):
import Alamofire
// ...
func fetchDataWithAlamofire() { AF.request("https://jsonplaceholder.typicode.com/todos/1") .validate() // 自动验证状态码在 200...299 范围内 .responseDecodable(of: Todo.self) { response in // 使用 Codable struct 'Todo' debugPrint(response) // 用于调试整个响应
switch response.result { case .success(let todoItem): print("Alamofire success! Title: \(todoItem.title)") // DispatchQueue.main.async { // self.myLabel.text = todoItem.title // } case .failure(let error): print("Alamofire request failed with error: \(error.localizedDescription)") } }}
// 为你期望的 JSON 响应定义一个 Codable structstruct Todo: Codable { let userId: Int let id: Int let title: String let completed: Bool}Alamofire 的 .responseDecodable 简化了将 JSON 解析为 Swift Codable 类型。它还提供了其他响应处理程序,如 .responseJSON、.responseData 和 .responseString。
这些是访问 iOS 中 Web 服务的基础知识。URLSession 功能强大且内置,而 Alamofire 为更复杂的场景提供了便利。始终优雅地处理错误,并在主线程/actor 上执行 UI 更新。对于身份验证、文件上传/下载和自定义请求配置等高级主题,请查阅 URLSession 的 Apple 官方文档或 Alamofire 文档。