Search code examples
swiftconcurrencyhttpwebrequestnsoperationqueue

swift serial queue operations out of order


I am trying to implement a serial queue, but for some reason the second block is being completed before the first block (as displayed in the system print. Any knowledge on why this is happening or how to fix it would be greatly appreciated!

SWIFT CODE:

func didAccept(with username: String) {
    
    let serialQueue = DispatchQueue(label: "acceptQueue")
    
    serialQueue.async {
        let url = URL(string: "http://127.0.0.1:5000/get-user-id")!
        var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        request.httpMethod = "POST"
        request.multipartFormData(parameters: ["username": username])
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data else { return }
            do {
                let requestList = try JSONDecoder().decode(TempId.self, from: data)
                self.friend_id = requestList.friend_id
                print("first: \(self.friend_id)")
            } catch let jsonErr {
                print(jsonErr)
            }
        }
        task.resume()
    }
    
    serialQueue.async {
        let url2 = URL(string: "http://127.0.0.1:5000/accept-decline-request")!
        var request2 = URLRequest(url: url2, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        request2.httpMethod = "POST"
        request2.multipartFormData(parameters: ["user_id": "17", "friend_id": "\(self.friend_id)", "response": "accept"])
        print("second: \(self.friend_id)")
        let task2 = URLSession.shared.dataTask(with: request2) { (data, response, error) in
            guard let data = data else { return }
        }
        task2.resume()
    }
    
    table.reloadData()
}

OUTPUT:

second: -1
first: 21

Solution

  • You can use Operation and operation queue for this requirement. You can set

    maxConcurrentOperationCount = 1
    

    It will call one request at one time. So until your firs't task's response won't come the second request will never be called. And once first request response came, second request will be automatically added in next queue.