iOS URLSession 網絡請求教學

URLSession 是 iOS 處理 HTTP 網路請求的標準 API。結合 Swift Concurrency,我們可以寫出非常簡潔的網路層程式碼。

基本 GET 請求

struct Post: Codable, Identifiable {
    let id: Int
    let title: String
    let body: String
}

class APIService {
    func fetchPosts() async throws -> [Post] {
        let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
        
        // 1. 發送請求
        let (data, response) = try await URLSession.shared.data(from: url)
        
        // 2. 檢查 HTTP 狀態碼
        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            throw URLError(.badServerResponse)
        }
        
        // 3. 解析 JSON
        return try JSONDecoder().decode([Post].self, from: data)
    }
}

在 View 中使用

struct PostListView: View {
    @State private var posts: [Post] = []
    
    var body: some View {
        List(posts) { post in
            VStack(alignment: .leading) {
                Text(post.title).font(.headline)
            }
        }
        .task { // View 出現時自動載入
            do {
                posts = try await APIService().fetchPosts()
            } catch {
                print("Error: \(error)")
            }
        }
    }
}

發送 POST 請求 (Upload Data)

func createPost(title: String) async throws {
    let url = URL(string: "https://api.example.com/posts")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let newPost = ["title": title]
    request.httpBody = try JSONEncoder().encode(newPost)
    
    let (_, response) = try await URLSession.shared.data(for: request)
    // check response...
}

現代 iOS 開發中,除非有特殊需求 (如複雜的 Authentication 流程管理),否則原生的 URLSession 已經足夠應付 90% 的場景,不再像以前那樣依賴第三方套件 (如 Alamofire)。