You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift应用通过WiFi向ESP32-CAM发送指定字符串的问题与修正

问题:Swift向ESP32-CAM发送指令异常

我是Swift新手,尝试通过WiFi给ESP32-CAM发送字符串指令,但无法正常工作。需求是:点击不同按钮发送对应字符串——点击“Enroll Face”发送“enroll”,点击“Delete All”发送“deleteA”,点击“Delete Last”发送“deleteL”,让ESP32-CAM执行对应任务(如删除所有ID、删除最后一个ID等)。

最初点击按钮时,ESP32-CAM收到的始终是POST / HTTP/1.1而非指定字符串,以下是初始代码和修改后改用JSON格式发送的代码。


初始代码

Swift代码

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()
    }

}

Arduino代码

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;
  }
}

修改后的代码

Swift代码(Enroll_Faces函数)

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()
}

Arduino代码(handleRequest函数)

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
  }
}

内容的提问来源于stack exchange,提问作者Wagner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:49:51