How i can pass the data to a variable in swift4? [duplicate]
How i can pass the data to a variable in swift4? [duplicate]
This question already has an answer here:
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)
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
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
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
//print(outputdata)
print("In the dataTask() closure: (outputdata)")
print(outputdata)
return
print("Before the return: (outputdata)")
1 Answer
1
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)
Are you sure request do not fail? Read data is not empty string encoding?
– Jean-Baptiste Yunès
Sep 14 '18 at 15:27