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.






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






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)

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)