Saltar a contenido

Ejemplos de Swift / iOS – API de Salud y Fitness

Utilice Swift para acceder a la API de Salud y Fitness desde sus aplicaciones de iOS. A continuación, se presentan ejemplos con URLSession y Alamofire nativos.


1. Utilizando URLSession

Ejemplo de solicitud GET:

import Foundation

let apiKey = "YOUR_API_KEY"
let url = URL(string: "https://api.hefitapi.com/api/v1/bmi?height=178&weight=82&units=metric&lang=en")!

var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error:", error)
        return
    }
    guard let data = data else { return }
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: [])
        print(json)
    } catch {
        print("Decoding error:", error)
    }
}

task.resume()

Ejemplo de solicitud POST:

import Foundation

let apiKey = "YOUR_API_KEY"
let url = URL(string: "https://api.hefitapi.com/api/v1/bmi/post")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")

let payload: [String: Any] = ["height": 178, "weight": 82, "units": "metric"]
request.httpBody = try? JSONSerialization.data(withJSONObject: payload, options: [])

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error:", error)
        return
    }
    guard let data = data else { return }
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: [])
        print(json)
    } catch {
        print("Decoding error:", error)
    }
}

task.resume()

2. Utilizando Alamofire (recomendado para una sintaxis más sencilla)

Instale Alamofire a través del Swift Package Manager:

// In Xcode: File > Swift Packages > Add Package Dependency
// URL: https://github.com/Alamofire/Alamofire.git

Ejemplo de solicitud GET:

import Alamofire

let apiKey = "YOUR_API_KEY"
let url = "https://api.hefitapi.com/api/v1/bmi"

AF.request(url, method: .get, parameters: ["height": 178, "weight": 82, "units": "metric", "lang": "en"], headers: ["X-API-Key": apiKey])
    .responseJSON { response in
        switch response.result {
        case .success(let value):
            print(value)
        case .failure(let error):
            print("Error:", error)
        }
    }

Ejemplo de solicitud POST:

import Alamofire

let apiKey = "YOUR_API_KEY"
let url = "https://api.hefitapi.com/api/v1/bmi/post"
let payload: [String: Any] = ["height": 178, "weight": 82, "units": "metric"]

AF.request(url, method: .post, parameters: payload, encoding: JSONEncoding.default, headers: ["X-API-Key": apiKey])
    .responseJSON { response in
        switch response.result {
        case .success(let value):
            print(value)
        case .failure(let error):
            print("Error:", error)
        }
    }

3. Notas y Mejores Prácticas

  • Utilice llamadas de red asíncronas para evitar bloquear el hilo principal.
  • Proteja siempre su clave de API; no la incluya en el código del lado del cliente que pueda ser revertido.
  • Las respuestas incluyen datos de _enterprise cuando sea aplicable para la supervisión y el seguimiento de cuotas.

Otros Lenguajes

Explore cómo integrar la API de Salud y Fitness en otros lenguajes de programación:

¡Comience a integrar la API de Salud y Fitness en sus aplicaciones hoy mismo!


API de Salud y Fitness Impulsando la infraestructura digital de salud moderna