Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Creating an OpenWeatherMap Account

To make the necessary requests to get data, you’ll first need to understand how to work with the OpenWeatherMap API. Head over to https://openweathermap.org and create an account. To make requests, you’ll need an API key. This will serve as your authorization to request data from this API. Below are the steps necessary to create an account and get your API Key.

Request Types

When working with RESTful APIs, you’ll encounter four primary HTTP methods: GET, POST, PUT, and DELETE. Each serves a specific purpose in CRUD (Create, Read, Update, Delete) operations. Here’s a basic explanation of each one:

  var request = URLRequest(url: url)
  request.httpMethod = "GET" // This is where you would set the various method types.

URLSession Network Request

To get started, download the materials from the repo and launch the SwiftyWeather project. Upon running the project, you should see a simple app with a search bar and instructions on how to type a city name and press enter. At the moment, this app doesn’t request to get data. You’re going to change that now.

@State private var searchText = ""
@State private var errorMessage: String?
var body: some View {
  NavigationStack {
    VStack {
      ContentUnavailableView(
        errorMessage ?? "Please type a city above and press enter",
        systemImage: "magnifyingglass"
      )
    }
  }
  .searchable(text: $searchText, prompt: Text("City Name"))
  .onSubmit(of: .search) {
  }
}
.onSubmit(of: .search) {
  // here, you will fetch the weather data
}
let apiKey = "YOUR API KEY HERE"
guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(searchText)&appid=\(apiKey)") else {
  print("Invalid URL")
  return
}
let session = URLSession.shared
let task = session.dataTask(with: url) { data, response, error in
    // Handle response here
}
task.resume()

Handling Errors

Error handling is an essential part of any application, especially one that makes network requests. Several types of errors can occur when requesting information from a server. Some errors are procedural, meaning there is a problem with how you made the request. Other errors are functional and can stem from how you process or parse a request.

if let error {
  print("Error: \(error.localizedDescription)")
  return
}
guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
  print("Invalid Response")
  return
}
guard let data else {
  print("No data received")
  return
}
print(String(data: data, encoding: .utf8) ?? "")
.onSubmit(of: .search) {
  let apiKey = "YOUR API KEY HERE"
  guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(searchText)&appid=\(apiKey)") else {
    print("Invalid URL")
    return
  }
  let session = URLSession.shared
  let task = session.dataTask(with: url) { data, response, error in
    if let error {
      print("Error: \(error.localizedDescription)")
      return
    }

    guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
      print("Invalid Response")
      return
    }

    guard let data else {
      print("No data received")
      return
    }
    print(String(data: data, encoding: .utf8) ?? "")
  }
  task.resume()
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Conclusion