我在我的应用程序的一部分中有这段代码:
let myUrl = NSURL(string: "http://aesolutions.ddns.net/data/load_tasks_calendar.php");
let request = NSMutableURLRequest(url: myUrl! as URL);
request.httpMethod = "POST";
let postString = "id_class=\(UserDefaults.standard.string(forKey: "userClass")!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
MenuViewController.tasksCalendarArray.removeAll()
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error1=\(String(describing: error))")
return
}
var _: NSError?
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON: NSArray = json {
for index in 0...parseJSON.count-1 {
if (parseJSON[index] is NSNull){
MenuViewController.tasksCalendarArray.removeAll()
}else{
let compito = parseJSON[index] as! [String:Any]
let task = tasks.init(taskId: compito["id"] as! String,taskType: compito["type"] as! String,taskSubject: compito["subject"] as! String,taskDate: compito["date"] as! String,taskComment: compito["comment"] as! String)
MenuViewController.tasksCalendarArray.append(task)
}
}
}
}catch{
print("error2=\(error)")
return
}
DispatchQueue.main.async(execute: {
self.performSegue(withIdentifier: "loginToDiary", sender: self)
});
}
task.resume();
我想在加载所有数组时才执行segue。我怎么能等到json终止或正确完成?因为我注意到有时它是正确的,有时它执行segue,因此数组是空的,然后在应用程序中有错误。 有人可以帮我添加一个带有“加载消息”的警报来等待阵列加载吗?