Answer the question
In order to leave comments, you need to log in
How to set internet access timeout in swift3?
Created a function to call php using the POST method to receive data, the output should receive an array of data of the type.
However, return is sent empty. It takes time to connect to the Internet and download the array. How to be?
var dataTake = ()
public class initInternet {
func dataArrayTake(urlPHPServer:String, sentKey: String, nameKey:String, id:Int, nameId:String ) ->
{
print("func: resultTake")
let url = URL(string:urlPHPServer)!
var request = URLRequest(url:url)
request.httpMethod = "POST";
let dataForm = "\(nameKey)=\(sentKey)&\(nameId)=\(id)"
request.httpBody = dataForm.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request)
{ data, response, error in
guard let data = data, error == nil else
{
print("ошибка данных:\(error)")
return
}
do
{
if let json = try? JSONSerialization.jsonObject(with: data) as! [String: Any]
{
let dataArray = json["result"] as!
dataTake = dataArray
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
{
print("Код ошибки: \(httpStatus.statusCode)")
print("Ошибка = \(response)")
}
}
task.resume()
return dataTake
}
}
Answer the question
In order to leave comments, you need to log in
For so many empty lines, you need to anally rape.
On the topic of the question:
The request is asynchronous, so the exit from the function occurs earlier than the request.
Outputs:
1) Synchronous request, which is terrible in most cases.
2) Pass a callback to the function, which will be called when the data is loaded.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question