0
0
iOS Swiftmobile~20 mins

POST request with JSON body in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: PostRequestScreen
This screen sends a POST request with a JSON body to a test API and shows the response.
Target UI
-------------------------
| Post Request Screen    |
|-----------------------|
| [Send POST Request]    |
|                       |
| Response:             |
| <response text here>  |
-------------------------
Add a button labeled 'Send POST Request'.
When tapped, send a POST request to https://jsonplaceholder.typicode.com/posts.
The POST request must include a JSON body with keys: title, body, userId.
Show the response JSON as a string below the button.
Handle errors by showing an error message in the response area.
Starter Code
iOS Swift
import SwiftUI

struct PostRequestScreen: View {
    @State private var responseText = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Post Request Screen")
                .font(.title)

            Button("Send POST Request") {
                // TODO: Add POST request code here
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)

            Text("Response:")
                .font(.headline)
                .frame(maxWidth: .infinity, alignment: .leading)

            ScrollView {
                Text(responseText)
                    .font(.body)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding()
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(8)
            }
            Spacer()
        }
        .padding()
    }
}

struct PostRequestScreen_Previews: PreviewProvider {
    static var previews: some View {
        PostRequestScreen()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
iOS Swift
import SwiftUI

struct PostRequestScreen: View {
    @State private var responseText = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Post Request Screen")
                .font(.title)

            Button("Send POST Request") {
                sendPostRequest()
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)

            Text("Response:")
                .font(.headline)
                .frame(maxWidth: .infinity, alignment: .leading)

            ScrollView {
                Text(responseText)
                    .font(.body)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding()
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(8)
            }
            Spacer()
        }
        .padding()
    }

    func sendPostRequest() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {
            responseText = "Invalid URL"
            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]

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: jsonBody)
            request.httpBody = jsonData
        } catch {
            responseText = "Failed to encode JSON body"
            return
        }

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                if let error = error {
                    responseText = "Error: \(error.localizedDescription)"
                    return
                }

                guard let data = data else {
                    responseText = "No data received"
                    return
                }

                if let jsonString = String(data: data, encoding: .utf8) {
                    responseText = jsonString
                } else {
                    responseText = "Failed to decode response"
                }
            }
        }
        task.resume()
    }
}

struct PostRequestScreen_Previews: PreviewProvider {
    static var previews: some View {
        PostRequestScreen()
    }
}

This solution creates a SwiftUI screen with a button labeled 'Send POST Request'. When the button is tapped, it calls sendPostRequest().

Inside sendPostRequest(), it builds a URLRequest with the POST method and sets the Content-Type header to application/json. It creates a dictionary with the required keys and converts it to JSON data.

The request is sent asynchronously using URLSession.shared.dataTask. When the response arrives, it updates the responseText state on the main thread to show the JSON response or an error message.

This approach keeps the UI responsive and clearly shows the server response below the button.

Final Result
Completed Screen
-------------------------
| Post Request Screen    |
|-----------------------|
| [Send POST Request]    |
|                       |
| Response:             |
| {                     |
|   "id": 101,         |
|   "title": "foo",   |
|   "body": "bar",    |
|   "userId": 1        |
| }                     |
-------------------------
User taps 'Send POST Request' button.
App sends POST request with JSON body to the API.
Response JSON is displayed below the button.
If error occurs, error message is shown instead.
Stretch Goal
Add a loading indicator that shows while the POST request is in progress.
💡 Hint
Use a @State Boolean to track loading state and show a ProgressView when true.