Browse Questions
  • You can add observers to stored properties you define, and to inherited stored or computed properties by overriding them in a subclass.
  • setNeedsLayout schedules a layout pass for later, layoutIfNeeded forces any pending layout to happen immediately, and setNeedsDisplay schedules a redraw of the view's content.
  • Define a clear error type, validate HTTP status codes, and propagate errors up to the UI where they can be shown to the user.
  • multipart/form-data is a content type used to send mixed data — like a file and text fields together — in a single request.

Answer: multipart/form-data is a content type used to send mixed data — like a file and text fields together — in a single request. Common for image/file uploads.

Code Example:

func uploadImage(_ image: UIImage, name: String) async throws {
    let url = URL(string: "https://api.example.com/upload")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let boundary = UUID().uuidString
    request.setValue("multipart/form-data; boundary=\(boundary)",
                     forHTTPHeaderField: "Content-Type")

    var body = Data()
    let imageData = image.jpegData(compressionQuality: 0.8)!

    // Add text field
    body.append("--\(boundary)\r\n".data(using: .utf8)!)
    body.append("Content-Disposition: form-data; name=\"name\"\r\n\r\n".data(using: .utf8)!)
    body.append("\(name)\r\n".data(using: .utf8)!)

    // Add image
    body.append("--\(boundary)\r\n".data(using: .utf8)!)
    body.append("Content-Disposition: form-data; name=\"file\"; filename=\"photo.jpg\"\r\n".data(using: .utf8)!)
    body.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
    body.append(imageData)
    body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

    request.httpBody = body
    let (_, _) = try await URLSession.shared.data(for: request)
}