This simple app fetches a post from the internet. It prints an error message if the call fails or prints the size of the data received. It uses DispatchQueue.main.async to update UI or print on the main thread.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1") else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
DispatchQueue.main.async {
print("Error fetching data: \(error.localizedDescription)")
}
return
}
guard let data = data else {
DispatchQueue.main.async {
print("No data received")
}
return
}
DispatchQueue.main.async {
print("Data received: \(data.count) bytes")
}
}.resume()
}
}