mardi 21 juin 2016

iOS URL Requests. Semaphore issues


I'm entering the concurrency programming with some semaphore issues. My function first loads data from server, analyze received info and then, if necessary, makes second request to server.

I tried different ways to make it run, none of them did it well. My current code FOR ME seems to be correct, but on second request it just locks(maybe like a DeadLock) and the last log is "<__NSCFLocalDataTask: 0x7ff470c58c90>{ taskIdentifier: 2 } { suspended }"

Please, tell me what do I don't know. Maybe there is more elegant way to work with completions for these purposes?

Thank you in advance!

var users = [Int]()
let linkURL = URL.init(string: "https://bla bla")
let session = URLSession.shared()
let semaphore = DispatchSemaphore.init(value: 0)
let dataRequest = session.dataTask(with:linkURL!) { (data, response, error) in
    let json = JSON (data: data!)
    if (json["queue"]["numbers"].intValue>999) {
        for i in 0...999 {
            users.append(json["queue"]["values"][i].intValue)
        }
        for i in 1...lround(json["queue"]["numbers"].doubleValue/1000) {
            let session2 = URLSession.shared()
            let semaphore2 = DispatchSemaphore.init(value: 0)
            let linkURL = URL.init(string: "https://bla bla")
            let dataRequest2 = session2.dataTask(with:linkURL!) { (data, response, error) in
                let json = JSON (data: data!)
                print(i)
                semaphore2.signal()
            }
            dataRequest2.resume()
            semaphore2.wait(timeout: DispatchTime.distantFuture)
        }
    }
    semaphore.signal()
}
dataRequest.resume()
semaphore.wait(timeout: DispatchTime.distantFuture)

P.S. Why do I do it. Server returns limited count of data. To get more, I have to use offset.


Aucun commentaire:

Enregistrer un commentaire