0

I'm sending the "formKATID" parameter to PHP. I want to send more than one "formKATID". For example, I want to select the data in the database where KATEGORI.ID = 6,7,8. That's why I have defined more than one formKATID in bodyObject. But it doesn't work that way. How can I submit more than one "formKATID"? I print the "ExistCount" row with json_encode and try to extract the count output by swift, but it comes with a null value. There is a problem with the Array I sent.

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()
}
11
  • What is the issue? Do you get an error in response? Your swift code looks right. Do you call task.resume()? Commented Apr 26, 2020 at 11:43
  • I print the "ExistCount" row with json_encode and try to extract the count output by swift, but it comes with a null value. There is a problem with the Array I sent. Commented Apr 26, 2020 at 11:52
  • I don't see errors in the code. Do you have an example of a valid request? You can create a request using Postman - postman.com. Commented Apr 26, 2020 at 12:14
  • When I try it in Postman, it returns null value, I think there is a problem with my php code. But I can't find the problem. @VladislavMarkov Commented Apr 26, 2020 at 12:21
  • I updated php code, Can you check it? Thank you. @VladislavMarkov Commented Apr 26, 2020 at 12:24

1 Answer 1

1

Your parameters are url encoded.

You should add it:

public extension String {

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

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

        return addingPercentEncoding(withAllowedCharacters: allowed)
    }

}

And you can try this:

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()
}
Sign up to request clarification or add additional context in comments.

4 Comments

@deneov I have updated my answer several times. Now it works.
@deneov Did you use my edited answer? I get the correct response and json object.
@deneov Your server uses http. Do you have a dictionary App Transport Security Settings with an element Allow Arbitrary Load with value YES in Info.plist?
Blank data came, thank you worked, you saved me from health :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.