You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Alamofire实现PUT请求以更新指定ID的API数据

Using Alamofire to Send PUT Requests for JSONPlaceholder Post Updates

Hey there! Let's break down exactly how to send a PUT request with Alamofire to update a post on the JSONPlaceholder API. I'll walk you through both basic and more type-safe approaches, since that's what folks usually find most useful.

First, Prep Your Updated Data

You can go with a simple dictionary for quick testing, but using a Codable model is way better for type safety in real apps. Here's both options:

Option 1: Dictionary (Quick & Dirty)

let updatedPost: [String: Any] = [
    "userId": 1,
    "id": 1,
    "title": "Updated: sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "Updated: quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
]

Define a Post struct that conforms to Codable to avoid typos and get autocompletion:

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

// Create your updated post instance
let updatedPost = Post(
    userId: 1,
    id: 1,
    title: "Updated: sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    body: "Updated: quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
)

Send the PUT Request

Now let's send the request to update the post. Remember, the URL needs to include the post ID you want to update (we're using ID 1 here).

Using the Dictionary Approach

import Alamofire

let targetURL = "https://jsonplaceholder.typicode.com/posts/1"

AF.request(targetURL, method: .put, parameters: updatedPost, encoding: JSONEncoding.default)
    .validate() // Automatically checks for 200-299 status codes
    .responseJSON { response in
        switch response.result {
        case .success(let returnedData):
            print("Update successful! Returned data: \(returnedData)")
            // You can parse this data further if needed
        case .failure(let error):
            print("Update failed: \(error.localizedDescription)")
            // Handle errors like network issues or invalid status codes here
        }
    }

Using the Codable Model Approach (Cleaner)

This approach automatically decodes the response back into your Post model, which is super convenient:

AF.request(targetURL, method: .put, parameters: updatedPost, encoder: JSONParameterEncoder.default)
    .validate()
    .responseDecodable(of: Post.self) { response in
        switch response.result {
        case .success(let updatedPost):
            print("Update successful! Here's the returned post:")
            print("ID: \(updatedPost.id)")
            print("Title: \(updatedPost.title)")
            print("Body: \(updatedPost.body)")
        case .failure(let error):
            print("Update failed: \(error.localizedDescription)")
            // Dig deeper into errors if needed
            if let afError = error as? AFError, case .responseValidationFailed(let reason) = afError {
                switch reason {
                case .unacceptableStatusCode(let code):
                    print("HTTP Status Code Error: \(code)")
                default:
                    break
                }
            }
        }
    }

A Quick Note

JSONPlaceholder is a mock API, so your updates won't actually persist on their servers. But it will return the updated data you sent as a response, which is perfect for testing your request logic.

Also, make sure you've properly integrated Alamofire into your project (via Swift Package Manager, CocoaPods, etc.) before running this code!

内容的提问来源于stack exchange,提问作者user9606220

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:44:23