1

I'm new to swift and I'm trying to send a string over to my ESP32-CAM using WiFi, but I can't make it work.

My goal is to send a different string over to my ESP32-CAM when I click different buttons and when he receives the string assign to the button he will perform different tasks such as: deleting all ids, deleting expected id etc...

When I try to send it, by clicking on the button, it sends the string " POST / HTTP/1.1" and it doesn't matter what button I click, it sends always the same string, and my goal is to send the string "enroll" when I press the button Enroll face , the string " DeleteA" when I press the button Delete all and the string "DeleteL" when I press the button Delete Last.

Here's my Swift code:

import SwiftUI
import Network

struct ContentView: View {
    @State private var isSending = false
    @State private var delete_A = false
    @State private var delete_L = false
    
    
    var body: some View {
        VStack {
            Spacer()
            Button(action: {
                isSending = true
                Enroll_Faces()
            }) {
                Text("Enroll Face")
                    .font(.system(size: 20, weight: .bold))
                    .foregroundColor(.white)
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.blue)
                            .shadow(color: Color.blue.opacity(0.5), radius: 5, x: 0, y: 5)
                    )
            }
            .opacity(isSending ? 0.5 : 1.0)
            
            Button(action: {
                delete_A  = true
                Delete_all()
            }) {
                Text("Delete All")
                    .font(.system(size: 20, weight: .bold))
                    .foregroundColor(.white)
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.blue)
                            .shadow(color: Color.blue.opacity(0.5), radius: 5, x: 0, y: 5)
                    )
            }
            .opacity(delete_A ? 0.5 : 1.0)
            
            .padding()
            
            Button(action: {
                delete_L  = true
                Delete_last()
            }) {
                Text("Delete Last")
                    .font(.system(size: 20, weight: .bold))
                    .foregroundColor(.white)
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 10)
                            .fill(Color.blue)
                            .shadow(color: Color.blue.opacity(0.5), radius: 5, x: 0, y: 5)
                    )
            }
            .opacity(delete_L ? 0.5 : 1.0)
            
            
            Spacer()
            
        }
    }

//---------------------------------------- FUNC ---------------------------------------------

    
    func Enroll_Faces() {
        guard let url = URL(string: "http://192.168.4.1") else {
            print("Invalid URL")
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        request.httpBody = "enroll".data(using: .utf8)
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                isSending = false
                if let error = error {
                    print("Failed to send string to access point: \(error.localizedDescription)")
                } else {
                    print("String sent successfully")
                   // checkDoorStatus()
                }
            }
        }
        
        task.resume()
    }
    func Delete_all() {
        guard let url = URL(string: "http://192.168.4.1") else {
            print("Invalid URL")
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "deleteA".data(using: .utf8)
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                delete_A = false
                if let error = error {
                    print("Failed to send string to access point: \(error.localizedDescription)")
                } else {
                    print("String sent successfully")
                }
            }
        }
        
        task.resume()
    }
    
    func Delete_last() {
        guard let url = URL(string: "http://192.168.4.1") else {
            print("Invalid URL")
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "deleteL".data(using: .utf8)
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                delete_L = false
                if let error = error {
                    print("Failed to send string to access point: \(error.localizedDescription)")
                } else {
                    print("String sent successfully")
                }
            }
        }
        
        task.resume()
    }

}

and this is my Arduino code:

     WiFiClient client = server.available();
          if (client)
          {
            Serial.println("New client connected!");
            String request = client.readStringUntil('\n');
            Serial.println(request);
            client.flush();
            if (request.indexOf("enroll") != -1)
            {
              Serial.println("ONE MORE");
              enroll = true;
            }
            else if (request.indexOf("deleteA") != -1)
            {
              Serial.println("Delete all!");
              delete_all = true;
            }
            else if (request.indexOf("deleteL") != -1)
            {
              Serial.println("Delete last!");
              delete_last = true;
            }
          }

Here is my final swift code :

func Enroll_Faces() {
        let stringToSend = "enroll"
        let urlString = "http://192.168.4.1"

        // Create the URL from the string
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }

        // Create the request
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        // Create the payload dictionary
        let payload = ["myString": stringToSend]

        // Convert the payload to JSON data
        guard let jsonData = try? JSONSerialization.data(withJSONObject: payload) else {
            print("Failed to convert payload to JSON data")
            return
        }

        // Set the request body as JSON data
        request.httpBody = jsonData

        // Set the appropriate headers
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.setValue(String(jsonData.count), forHTTPHeaderField: "Content-Length")

        // Print the payload being sent
        if let payloadString = String(data: jsonData, encoding: .utf8) {
            print("Payload being sent: \(payloadString)")
        }

        // Create a URLSession task
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("Error: \(error)")
                return
            }

            // Process the response
            if let data = data {
                let responseString = String(data: data, encoding: .utf8)
                print("Response: \(responseString ?? "")")
            }
        }

        // Start the task
        task.resume()
    }

and my Arduino code:

void handleRequest(WiFiClient client) {
  String requestHeaders = "";
  String requestBody = "";

  // Read the request headers
  while (client.available()) {
    String line = client.readStringUntil('\n');
    requestHeaders += line + '\n';
    if (line == "\r") {
      break;
    }
  }

  // Read the request body
  while (client.available()) {
    requestBody += (char)client.read();
  }
  // Parse the JSON payload
  DynamicJsonDocument doc(256);
  DeserializationError error = deserializeJson(doc, requestBody);

  if (error) {
    Serial.print("Failed to parse JSON payload: ");
    Serial.println(error.c_str());
    return;
  }

  // Retrieve the value of "myString" from the JSON payload
  String myString = doc["myString"].as<String>();

  // Handle the myString value
  if (myString == "enroll") {
    Serial.println("ONE MORE");

    // Handle the "enroll" case
    // Your code here
  } else if (myString == "deleteA") {
    Serial.println("Delete all!");

    // Handle the "deleteA" case
    // Your code here
  } else if (myString == "deleteL") {
    Serial.println("Delete last!");

    // Handle the "deleteL" case
    // Your code here
  }
  • 1
    "...but I can't make it work.", please edit your question and explain in a little more detail _what_ it is that doesn't work and _how_ it fails (unexpected result, error message, crash etc) – Joakim Danielson Jul 12 '23 at 10:24
  • Thanks for your help, I have already edited my question so it explains better what is my goal and what is not working properly. Best regards. – wagner daniel Jul 12 '23 at 12:33
  • I'm no expert on this but maybe you need to set some headers for the http request like "Content-Type" for instance. – Joakim Danielson Jul 12 '23 at 13:09
  • thanks I will try to set some headers and add somes prints to see if I catch the error. I have printed the payload Json in my swift code and It appear to be correct since it says Payload being sent: {"myString":"enroll"}, so I think the error might be in the Arduino code – wagner daniel Jul 12 '23 at 14:15
  • https://stackoverflow.com/questions/9254891/what-does-content-type-application-json-charset-utf-8-really-mean – Joakim Danielson Jul 12 '23 at 14:18
  • Thanks a lot, I finally got what I wanted thanks a lot mate – wagner daniel Jul 12 '23 at 15:16
  • If this hasn't worked for you, still, consider setting up a simple localhost node (or similar) server and send your requests there. That way you can log what is reaching your server and you know if your fault is with the Swift or the Arduino part. – Fab1n Jul 13 '23 at 13:20

0 Answers0