0
0
iOS Swiftmobile~5 mins

Error handling for network calls in iOS Swift

Choose your learning style9 modes available
Introduction

Network calls can fail for many reasons like no internet or server problems. Handling errors helps your app stay friendly and avoid crashes.

When fetching data from the internet like loading user info or images.
When sending data to a server, like submitting a form or uploading a photo.
When your app depends on online services and you want to show messages if something goes wrong.
Syntax
iOS Swift
URLSession.shared.dataTask(with: url) { data, response, error in
  if let error = error {
    // Handle error here
    print("Error: \(error.localizedDescription)")
    return
  }
  // Use data if no error
}.resume()
Use the error parameter to check if the network call failed.
Always call .resume() to start the network task.
Examples
This example prints an error message if the call fails, or prints the size of data received if successful.
iOS Swift
URLSession.shared.dataTask(with: url) { data, response, error in
  if let error = error {
    print("Network error: \(error.localizedDescription)")
    return
  }
  if let data = data {
    print("Data received: \(data.count) bytes")
  }
}.resume()
This uses guard statements to handle errors and missing data clearly.
iOS Swift
URLSession.shared.dataTask(with: url) { data, response, error in
  guard error == nil else {
    print("Failed with error: \(error!.localizedDescription)")
    return
  }
  guard let data = data else {
    print("No data received")
    return
  }
  print("Success with data size: \(data.count)")
}.resume()
Sample App

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.

iOS Swift
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()
  }
}
OutputSuccess
Important Notes

Always check the error parameter first to catch network problems.

Use DispatchQueue.main.async to update UI or print from network callbacks.

Remember to call .resume() to start the network request.

Summary

Network calls can fail; always check for errors.

Use the error parameter in the completion handler to detect problems.

Update UI on the main thread after network responses.