-2

I need to use the output data in another viewcontroller but I can't use, the string only returns an empty string :

func callApi(postString: String) -> (String) {
    var outputdata = String()
    var req = LogIn(postString: postString)
    let task = URLSession.shared.dataTask(with: req) { (data, response, error) in
        if let data = data{
            outputdata = String(data: data, encoding: String.Encoding.utf8)!
            //print(outputdata)


        }
    }

    print(outputdata)
    return (outputdata)
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Erick Arciniega
  • 96
  • 1
  • 1
  • 5
  • Are you sure request do not fail? Read data is not empty string encoding? – Jean-Baptiste Yunès Sep 14 '18 at 15:27
  • You need to resume the task to get the result .. 'task.resume()' and this is asynronous request so you can not use return here, use closure instead. – TheTiger Sep 14 '18 at 15:29
  • 1
    The concept your are missing is "Asynchrone". If instead of `//print(outputdata)` you do `print("In the dataTask() closure: \(outputdata)")`, and instead of `print(outputdata)` (just before the `return`) you do `print("Before the return: \(outputdata)")`, you'll that the order of prints you think isn't the one. Look for "Swift + Closure + Async" to mange that. – Larme Sep 14 '18 at 15:30

1 Answers1

-2

You can try this as the process is asynchronous

func callApi(_ postString: String,completion:@escaping:(_ res:String?) -> Void ) {
     var req = LogIn(postString: postString)
    URLSession.shared.dataTask(with: req) { (data, response, error) in
        if let data = data{
            completion(String(data: data, encoding: String.Encoding.utf8))     
        }
        else {
            completion(nil)
        }
    }.resume()
 }

Call

callApi("SendedValue") {  res in
  print(res)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87