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

时间:2019-02-24 06:59:10

标签: ios json swift http urlsession

我正在创建一个基本的iOS移动应用,以通过直接通过WiFI并使用HTTP POST REQUEST连接来在相机设备上捕获图像。

要捕获图像,该功能必须触发两(2)条命令。一(1)激活快门,一(1)释放快门。因此,此特定命令需要按顺序执行两次。

这是摄像机的“ POST请求”格式:

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

我首先检查是否可以检索有关该设备的信息:

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

这将产生以下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;
}

然后我继续执行第一个触发器:

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

这将产生以下JSON响应:

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

我不确定我在做什么以获取无效的参数。

请检查。

我应该如何编码该应用程序以依次执行(2)HTTP POST请求以打开和关闭快门?

1 个答案:

答案 0 :(得分:0)

使用DispatchGroup()解决您的问题。我将尝试在下面提供一些示例代码:

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