connect to gamedb api in swift

You can use Swift’s built-in URLSession class to make a connection to a RESTful API like Gamedb.

Here is an example code to connect to the Gamedb API and fetch data for a game by its name:

main.swift
let gameName = "Overwatch"
let queryString = gameName.replacingOccurrences(of: " ", with: "%20")

if let url = URL(string: "https://api.rawg.io/api/games?search=\(queryString)") {
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }
        guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
            print("Error: invalid response")
            return
        }
        guard let data = data else {
            print("Error: no data returned")
            return
        }
        do {
            let gameData = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            if let results = gameData?["results"] as? [[String: Any]],
                let game = results.first {
                print(game["name"])
                print(game["released"])
                // etc...
            }
        } catch let error {
            print("Error: \(error.localizedDescription)")
        }
    }
    task.resume()
}
1149 chars
32 lines

In this example, we are searching for a game by its name using the search parameter in the URL. After verifying that we received a valid response with our game data, we parse it into a dictionary using JSONSerialization. We then extract the relevant data from the dictionary and print it to the console.

Note that you will need to replace the URL in this example with the specific endpoint for the Gamedb API that you want to use. Additionally, you should consider implementing error handling and response-parsing logic based on the specific requirements of your app.

related categories

gistlibby LogSnag