Explicación sobre cómo crear el API https://www.jesusninoc.com/07/30/crear-un-api-en-python-con-flask-que-inserte-y-lea-valores-en-firebase-y-desplegarlo-en-vercel/
Código en Swift para Apple Watch que inserta un valor mediante una petición POST
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
import SwiftUI struct ContentView: View { @State private var valueToSend: String = "" @State private var responseMessage: String = "" @State private var showAlert: Bool = false var body: some View { VStack { TextField("Ingresa un valor", text: $valueToSend) .textFieldStyle(PlainTextFieldStyle()) .padding() .background(Color.black) .cornerRadius(8) .padding([.leading, .trailing]) Button(action: sendPostRequest) { Text("Enviar") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .alert(isPresented: $showAlert) { Alert(title: Text("Respuesta del servidor"), message: Text(responseMessage), dismissButton: .default(Text("OK"))) } } .navigationTitle("Enviar datos") .padding() } func sendPostRequest() { guard let url = URL(string: "https://asfasfsfd/add") else { responseMessage = "URL inválida" showAlert = true return } let data = ["value": valueToSend] guard let jsonData = try? JSONSerialization.data(withJSONObject: data) else { responseMessage = "Error al crear JSON" showAlert = true return } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = jsonData URLSession.shared.dataTask(with: request) { data, response, error in let resultMessage: String if let error = error { resultMessage = "Error de red: \(error.localizedDescription)" } else if let data = data { if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 { do { let responseJSON = try JSONSerialization.jsonObject(with: data) resultMessage = "Respuesta del servidor: \(responseJSON)" } catch { resultMessage = "Error al decodificar JSON: \(error.localizedDescription)" } } else { resultMessage = "Respuesta del servidor: \(String(data: data, encoding: .utf8) ?? "Desconocida")" } } else { resultMessage = "No se recibieron datos" } DispatchQueue.main.async { responseMessage = resultMessage showAlert = true } }.resume() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |