Bringing an API item to Swift

0

let httpStatus = response as? HTTPURLResponse
if httpStatus?.statusCode == 200 {
if data?.count != 0 {
    let respJson = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
    if let codigo = respJson ["codigo" as! Int]{
        print("Codigo: \(codigo)")
        DispatchQueue.main.sync {}
    }
}
    
asked by anonymous 25.09.2017 / 15:59

2 answers

0

Is not it missing a key in the code?

let httpStatus = response as? HTTPURLResponse
if httpStatus?.statusCode == 200 {
    if data?.count != 0 {
        let respJson = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
        if let codigo = respJson ["codigo" as! Int]{
            print("Codigo: \(codigo)")
            DispatchQueue.main.sync {}
        }
    }
}
    
25.09.2017 / 16:10
0

Response made taking into account published code here . Your problem is that you are executing a non-synchronized method so when you try to print the result of starting your get the result kinda naoto establishment available. What you need is to move your print to the closure denture of your non-synchronized method and add a completion handler to your Initial Indicators method and pass the result back when finished from within your closure:

Note: Since you have not posted your JSON I can not tell if it contains one or more rescissions. If it contains more than one you will have to do the sum within the contained loop of the dictionaries and call the completion handler after the loop is completed.

func indicadores(completion: @escaping (_ qdeRescisao: Int?, _ error: Error?) -> Void) {
    let headers = [
        "Content-Type": "application/json",
        "Authorization":"\(UserDefaults.standard.string(forKey: "correctToken")!)"
    ]
    var request = URLRequest(url: URL(string: "http://10.1.80.106:9000/api/indicadores")!)
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers
    URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else {
            completion(nil, error)
            return
        }
        do {
            if let dictionaries = (try JSONSerialization.jsonObject(with: data)) as? [[String: Any]] {
                for dictionary in dictionaries {
                    if let codigo = dictionary["codigo"] as? String, codigo == "rescisao", let qdeRescisao = dictionary["quantidade"] as? Int {
                        completion(qdeRescisao, nil)
                    }
                }
            }
        } catch {
            completion(nil, error)
            return
        }
    }.resume()
}

How to call the method not synchronized with the completion handler:

indicadores { qdeRescisao, error in
    guard let qdeRescisao = qdeRescisao else {
        print(error?.localizedDescription ?? "nil")
        return
    }
    self.qtdTotalRescisao += qdeRescisao
    print("qtdTotalRescisao:", self.qtdTotalRescisao)
}
    
14.02.2018 / 04:42