0

at my form load, i need to get a data from json string and push it into an arraylist. When i check my code with breakpoints, my cursor enters my method, going through, and it get task2, pass "if" then stopped at var sec="" then exit my method, after 2-3 seconds, it enters do for. Whats wrong with my code?

 override func viewDidLoad() {
    super.viewDidLoad()
    let urlJsonToken2 = "https://services.domain.com/"
    let myURL2 = NSURL(string: urlJsonToken2)
    let request2 = NSMutableURLRequest(url: myURL2! as URL)
    request2.httpMethod = "GET"
    request2.addValue("Bearer "+tokenNewId, forHTTPHeaderField: "Authorization")
    request2.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
    request2.setValue("application/json", forHTTPHeaderField: "Accept")
    let task2 = URLSession.shared.dataTask(with: request2 as URLRequest) {(data2, response2, error2) -> Void in
        if let unwrappedData2 = data2 {
            do {
                guard let records = try? JSONSerialization.jsonObject(with: unwrappedData2, options: .mutableContainers) as? [[String: Any]] else {
                    return
                }
                for item in records! {
                    let id = item["id"] as? intmax_t
                    let name = item["name"] as? String
                    self?.ArrayList.append(ClassCat(id:id!, id: name!, name));
                }
            } catch {}
        }
    } task2.resume()
    var sec = ""
}
Larme
  • 24,190
  • 6
  • 51
  • 81
Kuroiteiken
  • 308
  • 3
  • 15
  • You are aware that the web call is asynchronous? – Larme Apr 06 '18 at 12:11
  • URLSession.shared.dataTask is asynchronous. You need to use a callback (completion handler) to get the content out of the closure. Follow the examples I've given. – Eric Aya Apr 06 '18 at 12:12
  • We tried but i'll provide a gif link for my problem. http://www.ibbmeslekfabrikasi.com/IMG_6227.GIF please check it. – Kuroiteiken Apr 09 '18 at 10:25

0 Answers0