0

I have this code in a part of my app:

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();

I want to perform the segue only when I load all the array. How can I wait until the json is terminated or is done correctly? Because I noticed that sometimes it is correct and other times it performs the segue and so the array is empty and then in the app there are errors. Can someone help me also adding an alert with a kind of "loading message" to wait that the array is loading?

Marco
  • 65
  • 11
  • Side note: `var _: NSError?` doesn't make any sense. Not only you don't need to declare the error prior to use a catch block, but here you discard it immediately, which is 100% useless. – Eric Aya Sep 22 '17 at 10:51
  • 1
    You need to use a callback. Follow this example: https://stackoverflow.com/a/31264556/2227743 It's for a string, so you want to apply the same idea but for your content (a Task, for example). – Eric Aya Sep 22 '17 at 11:01

0 Answers0