connect to a strapi server in swift

To connect to a Strapi server in Swift, you can use Swift's built-in URLSession class to make HTTP requests to the Strapi API. Here's an example of using URLSession to make a GET request to retrieve data from a Strapi server:

main.swift
guard let url = URL(string: "http://localhost:1337/articles") else { return }

var request = URLRequest(url: url)
request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("Error connecting to Strapi server: \(error?.localizedDescription ?? "unknown error")")
        return
    }

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
        print("Error connecting to Strapi server: HTTP status code \(httpStatus.statusCode)")
        return
    }

    // Do something with the data
    print(String(data: data, encoding: .utf8))
}

task.resume()
692 chars
22 lines

In this example, we first create a URL for the Strapi server's "articles" endpoint. We then create a URLRequest object and set its httpMethod property to "GET". We use URLSession's dataTask method to create a task that retrieves the data from the Strapi server. In the task's completion handler, we check for any errors and HTTP statuses, and then use the retrieved data for further processing.

Note that http://localhost:1337 should be replaced with your Strapi server's URL, and articles should be replaced with your desired API endpoint. Additionally, you might need to modify the example code to suit your specific use case.

gistlibby LogSnag