繁体   English   中英

将数组作为 POST 请求参数发送到 PHP - Swift

[英]Send array as POST request parameter to PHP - Swift

我将“formKATID”参数发送到 PHP。 我想发送多个“formKATID”。 比如我想select数据库中KATEGORI.ID = 6,7,8的数据。 这就是为什么我在bodyObject 中定义了多个formKATID。 但它不是那样工作的。 如何提交多个“formKATID”? 我使用 json_encode 打印“ExistCount”行并尝试通过 swift 提取计数 output,但它带有 null 值。 我发送的阵列有问题。

PHP
...

     $connectionInfo = array( "UID"=>$uid,
                                "PWD"=>$pwd,
                                "Database"=>$databaseName);

    $conn = sqlsrv_connect($serverName, $connectionInfo);

    $formKATID = $_POST['formKATID'];

    $tsql = "SELECT ... IN(".implode(', ',$formKATID).")";
    $stmt = sqlsrv_query( $conn, $tsql);

    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {

        $paketCount = $row['ExistCount'];

         $results[] = Array("Count" => $paketCount);
    }
     echo json_encode($results, JSON_UNESCAPED_UNICODE);
    sqlsrv_free_stmt( $stmt);
    ?>

...

SWIFT

@objc func kategoriSaydır(){
    var request = URLRequest(url: url)
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.httpMethod = "POST"

    let bodyObject = ["formKATID": ["6", "7", "8"]] as [String : Any]
    request.httpBody = try! JSONSerialization.data(withJSONObject: bodyObject, options: [])

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else {
            // error
            return
        }
        do {
            if let baslik = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
                for review in baslik {
                    if let soru_baslik = review["Count"] as? String {
                        let s = String(describing: soru_baslik)
                        print("kategoriItemCount", s)
                    }
                }
            }
        } catch let parseError { ... }
    }
    task.resume()
}

您的参数是 url 编码的。

你应该添加它:

public extension String {

    public func addingPercentEncodingForUrlQueryValue() -> String? {
        let generalDelimitersToEncode = ":#[]@"
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

        return addingPercentEncoding(withAllowedCharacters: allowed)
    }

}

你可以试试这个:

func generateParametersString(_ parameters: [String: Any]) -> String {
    let parameterArray = parameters.map { key, value -> String in
        guard let escapedKey = key.addingPercentEncodingForUrlQueryValue() else { return "" }

        if let stringValue = value as? String {
            guard let escapedValue = stringValue.addingPercentEncodingForUrlQueryValue() else { return "" }

            return "\(escapedKey)=\(escapedValue)"
        }

        if let arrayValue = value as? [Any] {
            var arrayParameter: [String] = []

            for index in 0..<arrayValue.count {
                var element: String
                if let stringElement = arrayValue[index] as? String {
                    element = stringElement
                } else {
                    element = "\(arrayValue[index])"
                }

                guard let escapedElement = element.addingPercentEncodingForUrlQueryValue() else { continue }

                arrayParameter.append("\(escapedKey)[]=\(escapedElement)")
            }

            return arrayParameter.joined(separator: "&")
        }

        guard let escapedValue = "\(value)".addingPercentEncodingForUrlQueryValue() else { return "" }

        return "\(escapedKey)=\(escapedValue)"
    }

    return parameterArray.joined(separator: "&")
}

@objc func kategoriSaydır(){
    var request = URLRequest(url: url)
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.httpMethod = "POST"

    let bodyObject = ["formKATID": ["6", "7", "8"]] as [String : Any]
    request.httpBody = generateParametersString(bodyObject).data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else {
            // error
            return
        }
        do {
            if let baslik = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
                for review in baslik {
                    if let soru_baslik = review["Count"] {
                        let s = String(describing: soru_baslik)
                        print("kategoriItemCount", s)
                    }
                }
            }
        } catch let parseError { ... }
    }
    task.resume()
}

暂无
暂无

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

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