Swift - saving values from a thread to a variable

Hi,
I have 2 variables:

var hallOfFame = “”
var hallOfFameGrupy = “”

and 2 threads:

func downloadRankingPersonal(adress : String, adress2 : String, completed: @escaping () → ()){
let url = URL(string: adress)
let idGry = self.wybranaGra!.id!
print(“Startuje 1 wątek”)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
var statusRanking = “”
do {
Alamofire.request(adress, method: .get, parameters: nil)
.responseJSON { response in
let jsonResponse = JSON(response.result.value!)
if (jsonResponse[“stanyGry”][0][“email”].string == “” || jsonResponse[“stanyGry”][0][“email”].string == nil){
statusRanking = “0”
} else{
statusRanking = jsonResponse[“stanyGry”][0][“email”].string!
self.hallOfFame = statusRanking
}
}
.responseString { response in
if let error = response.result.error {
print(error)
}
if let value = response.result.value {
print(value)
}
}

            DispatchQueue.main.async {
                self.hallOfFame = statusRanking
                self.downloadRankingGroup(adress: adress2){
                }
                
                completed()
            }
        } catch {
            print("JSON ERROR")
            self.hallOfFame = ""
        }
    }
    }.resume()

}

func downloadRankingGroup(adress : String, completed: @escaping () → ()){
let url = URL(string: adress)
let idGry = self.wybranaGra!.id!
print(“Startuje 2 wątek”)
print(“adress 2: (adress)”)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
var statusRanking = “”
do {
Alamofire.request(adress, method: .get, parameters: nil)
.responseJSON { response in
let jsonResponse = JSON(response.result.value!)

                    let grupy = jsonResponse["ranking"]["grupy"].array
                    if (grupy!.count > 0) {
                        statusRanking = "1"
                        self.hallOfFameGrupy = statusRanking
                        print("ilosc rekordow: \(grupy!.count)")
                    } else {
                        statusRanking = "0"
                    }
                    
                    
                }
                .responseString { response in
                    if let error = response.result.error {
                        print(error)
                    }
                    if let value = response.result.value {
                        print(value)
                    }
            }
            DispatchQueue.main.async {
                self.hallOfFameGrupy = statusRanking
                if(self.hallOfFame != "" && self.hallOfFameGrupy != "") {
                    self.checkCodeRankingAlert()
                }
                completed()
            }
        } catch {
            print("JSON ERROR")
            self.hallOfFameGrupy = ""
        }
    }
    }.resume()

}

After running these two threads, I would like to complete the following variables: hallOfFame and hallOfFameGrupy, but unfortunately the results of threads are not saved in variables. CurrentQueue
Does anyone know how to fix it?

@trifek Thanks very much for your question!

Right off the bat, I have to ask, why are you using both URLSession AND Alamofire in your project? I think this is a serious mistake. You should use one or the other, but not both. Another problem I noticed is that you’re not using Swift 4’s Codable protocol to help with your JSON parsing, this will make your life a lot easier, and your code much more readable, and simpler. The other thing I wish to point out is that your UI code is to run on your main thread. However, you’re simply updating variables on it. You should keep your main thread for updating the UI and nothing else.

This should be a good start!

@syedfa,
there are projects (though they are bad practices) on enterprise level by big consulting name developers (that people know across countries and continents) that use multiple methodologies. I agree with you that this is BAD (emphasized in caps and bold). In larger enterprise project this happens due to the fullstack developer that take a vertical and use whatever they need for that one task they are working on. In smaller projects it is a similar phenomenon called stackoverflow or copy/paste programming.

Another thing that got me interested in this was what do you think is better, Alamofire’s JSON handling or Swift4’s JSON handling? Personally I prefer to use URLSession and Swift4 JSON parsing, however in legacy projects with Obj-C (yes they exist and are still there with the issues mentioned above) libraries like AFNetworking and JSONModel (from our own Marin Todorov)

and yes you have raised a very good point that many developers fail to look into is when using URLSession they end up with running UI code on the background thread.

cheers,

Jayant

This topic was automatically closed after 166 days. New replies are no longer allowed.