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
}