We use POST requests with JSON body to send data from your app to a server. This helps you save or update information online.
0
0
POST request with JSON body in iOS Swift
Introduction
When a user submits a form like signing up or logging in.
When sending a message or comment to a chat or social app.
When uploading settings or preferences to your account.
When creating a new item like a post, photo, or task in an app.
Syntax
iOS Swift
let url = URL(string: "https://example.com/api")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let json: [String: Any] = ["key": "value"] let jsonData = try? JSONSerialization.data(withJSONObject: json) request.httpBody = jsonData let task = URLSession.shared.dataTask(with: request) { data, response, error in // handle response here } task.resume()
Set the HTTP method to "POST" to tell the server you want to send data.
Set the "Content-Type" header to "application/json" to specify the data format.
Examples
Send login info as JSON in the POST request body.
iOS Swift
var request = URLRequest(url: URL(string: "https://api.example.com/login")!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let body = ["username": "user1", "password": "pass123"] request.httpBody = try? JSONSerialization.data(withJSONObject: body)
Create a new task by sending its details as JSON.
iOS Swift
var request = URLRequest(url: URL(string: "https://api.example.com/tasks")!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let taskData = ["title": "Buy milk", "done": false] as [String : Any] request.httpBody = try? JSONSerialization.data(withJSONObject: taskData)
Sample App
This example sends a POST request with a JSON body to a test API. It prints the server's JSON response in the console.
iOS Swift
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() sendPostRequest() } func sendPostRequest() { guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let jsonBody: [String: Any] = ["title": "foo", "body": "bar", "userId": 1] request.httpBody = try? JSONSerialization.data(withJSONObject: jsonBody) let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error.localizedDescription)") return } guard let data = data else { print("No data received") return } if let responseJSON = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { print("Response JSON: \(responseJSON)") } } task.resume() } }
OutputSuccess
Important Notes
Always set the Content-Type header to "application/json" when sending JSON data.
Use URLSession's dataTask to send the request asynchronously.
Handle errors and check the response to know if the request succeeded.
Summary
POST requests send data to a server, often to create or update something.
JSON is a common format to send structured data in the request body.
Set the HTTP method and headers correctly to make the server understand your data.