Swift:
Надсилання HTTP-запиту
How to: (Як це зробити:)
import Foundation
let url = URL(string: "https://api.example.com/data")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
} else if let data = data,
let string = String(data: data, encoding: .utf8) {
print(string)
}
}
task.resume()
Output:
{"data": "some value"}
Deep Dive (Поглиблене занурення)
Sending HTTP requests is a basic yet powerful way to interact with the web. It began with simple web pages, evolved with the internet, and now it’s essential for modern apps. Compared to other methods like WebSocket, HTTP requests are stateless and good for standalone operations. Underneath, they work by establishing a TCP connection, sending plain-text commands (GET, POST, etc.), and listening for a response.
See Also (Дивіться також)
- Apple’s URLSession documentation: URLSession | Apple Developer Documentation
- Swift’s official HTTP networking guide: Networking Overview | Swift.org
- An article on RESTful APIs: Understanding RESTful APIs