简体   繁体   English

如何使用URLSession(Swift 4.2)触发两(2)个HTTP POST请求?

[英]How Can I Trigger Two (2) HTTP POST REQUESTS Using URLSession (Swift 4.2)?

I am creating a basic iOS mobile app to capture an image on my camera device by connecting directly via WiFI and using HTTP POST REQUEST. 我正在创建一个基本的iOS移动应用程序,以通过直接通过WiFI连接并使用HTTP POST REQUEST连接来捕获相机设备上的图像。

To capture an image, the function must trigger two (2) commands. 要捕获图像,该功能必须触发两(2)条命令。 One (1) to activate the shutter and one (1) to release the shutter. 一(1)激活快门,一(1)释放快门。 So this specific command needs to be executed 2x sequentially. 因此,此特定命令需要按顺序执行两次。

This is the format of the POST REQUEST to the camera: 这是向摄像机发送请求的格式:

REQUEST TO TAKE A PICTURE
POST
camera_API_URL
{
"action": "half_press",
"af": “true”
}

REQUEST TO STOP TAKING A PICTURE
POST
camera_API_URL
{
"action": "release",
"af": “false”
}

I first check to see if I can retrieve information about the device: 我首先检查是否可以检索有关该设备的信息:

    guard let url = URL(string: "camera_API_URL") else { return }

        let session = URLSession.shared
        session.dataTask(with: url) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            print(data)
            do {
                let json = try JSONSerialization.jsonObject(with: data,   options: [])
                print(json)
            } catch {
                print(error)
            }
        }
       }.resume()

This yields the following JSON data response: 这将产生以下JSON数据响应:

<NSHTTPURLResponse: 0x283bb96c0> { URL: camera_API_URL } { Status Code: 200,   Headers {
"Content-Length" =     (
    199
);
"Content-Type" =     (
    "application/json"
);
} }
199 bytes
{
firmwareversion = "1.0.1";
guid = 1q2w3e4r5t6y7u8i9o0p;
macaddress = "04:1f:2e:12:1d:93";
munufacturer = "Some Company";
productname = "DSLR Camera Name";
serialnumber = 1234567890;
}

I then proceed to do the first trigger: 然后,我继续执行第一个触发器:

    let parametersOpenShutter = ["action": "half_press", "af": "true"]
    let parametersCloseShutter = ["action": "release", "af": "false"]

    guard let url = URL(string: "camera_API_URL") else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parametersOpenShutter, options: []) else { return }
    request.httpBody = httpBody

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
        }

        }.resume()

This yields the following JSON response: 这将产生以下JSON响应:

<NSHTTPURLResponse: 0x2825bfa80> { URL: camera_API_URL } { Status Code: 400,   Headers {
"Content-Length" =     (
    31
);
"Content-Type" =     (
    "application/json"
);
} }
{
message = "Invalid parameter";
}

I am unsure what I am doing wrong to get an invalid parameter. 我不确定我做错了什么来获取无效的参数。

Please check. 请检查。

How should I code the app to perform (2) HTTP POST REQUESTS sequentially to open and close the shutter? 我应该如何编码应用程序以依次执行(2)HTTP POST请求以打开和关闭快门?

Use DispatchGroup() to resolve your problem. 使用DispatchGroup()解决您的问题。 I'll try to give some sample code below: 我将尝试在下面给出一些示例代码:

//Create a dispatch group
let group = DispatchGroup()
//Make first web service call
group.enter()
webservice.firstCall { (response, error) in
    //.....handle the response
    group.leave()
} 
//Make second web service call
group.enter()
webservice.secondCall { (response, error) in
    //.... handle the response
    group.leave()
} 

// Add the observer when all the tasks in the group are completed.
group.notify(queue: .main) { [weak self] in
   //Handle completion of web service calls
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM