0

I have simple function, which works with one exception.

static func configSessionAndSend(request: URLRequest) -> Character {
        // Create and run a URLSession data task with our JSON encoded POST request
        var responseChar: Character = "1"
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        let task = session.dataTask(with: request) { (responseData, response, responseError) in
            guard responseError == nil else {
                //TODO: error handling
                return
            }

            // APIs usually respond with the data you just sent in your POST request

            if let data = responseData, let utf8Representation = String(data: data, encoding: .utf8), let httpUrlResponse = response as? HTTPURLResponse {

                responseChar = StringHelper.getSecondLetter(stringValue: utf8Representation)
                print("response: ", utf8Representation) //print server response
                //print(httpUrlResponse.allHeaderFields) //print server headers
                print("server response status: ", httpUrlResponse.statusCode) //print status code; use this later to check if 200 all OK
                print("server respose char: ", responseChar)
            } else {
                print("no readable data received in response")

            }
        }

        task.resume()
        return responseChar

    }

My server return 0 as it should, and I am modifing variable responseChar and print("server respose char: ", responseChar) gives proper value when it is inside if statement. But return responseChar returns 1 like my initial variable was never modified? What am I doing wrong?

Robert
  • 525
  • 1
  • 6
  • 21
  • 1
    If your code was ever working as you expected it would not compile. You would get a compiler error *Cannot return Void for a non-Void returning function* in the line with the single `return` statement. – vadian May 01 '18 at 09:52
  • So I converted static `static func configSessionAndSendNew(request: URLRequest, completionHandler: @escaping (_ returned: Character) -> ()) -> Void {completionHandler(responseChar)}` and now call function `JsonHelper.configSessionAndSendNew(request: req) { returned in returnedValue = returned }` but it is still the same - returnedValue within is 0, outside is 1. What's wrong? how to assigned handler value `returned` to external variable `returnedValue` – Robert May 01 '18 at 18:05

0 Answers0