Swift:减少对WebService的多次调用

时间:2017-02-16 21:25:07

标签: swift web-services asynchronous

我正在开发一个向web服务发送多个请求的应用程序。随着我的进一步发展,我发现网络服务越来越不堪重负,我需要放慢速度。我想将每个请求单独发送到Webservice并等到上一个请求完成后再发送下一个请求。这是使用循环来调用webservice的函数:

$(elt).closest('td:not(.savedBlock)').remove() 

HTTPPost函数如下所示:

func syncronize(){

    for operation in syncOperations{
        switch operation{
            case "listPhone":
            let listRequest = WSListRequest(requestType: operation, searchCriteria: [SearchCriteria(name: "name", value: "%")], returnTags: [])
            _ = HTTPPost(method: "POST", body: listRequest.xml, operation: operation, credentials: creds)
        default:
            let listRequest = WSLListRequest(requestType: operation, searchCriteria: [SearchCriteria(name: "name", value: "%")], returnTags: ["name"])
            _ = HTTPPost(method: "POST", body: listRequest.xml, operation: operation, credentials: creds)
        }
    }
}

对于Asyncronous编程,我是一个新手,可以使用一些帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

使用信号量,以便在上一个任务完成之前不会开始执行任务。这是一个演示

// The semaphore value is like the size of a token pool. After you've taken
// all the tokens in the pool, you must wait until a task returns its token
// back to the pool. Here we only have 1 token (1 request at a time)
let semaphore = DispatchSemaphore(value: 1)

// task1 is a request that will take at least 5 seconds to respond
let task1 = URLSession.shared.dataTask(with: URL(string: "https://httpbin.org/delay/5")!) { data, response, error in
    print("Task1 is done")
    semaphore.signal()  // release the token
}

// task2 is a faster request
let task2 = URLSession.shared.dataTask(with: URL(string: "https://httpbin.org")!) { data, response, error in
    print("Task2 is done")
    semaphore.signal()  // release the token
}

// Never wait on your main queue, always do that in the background
DispatchQueue.global(qos: .background).async {
    semaphore.wait() // take a token, wait if needed.
                     // There will never be a wait here, but included for consistency
    print("starting task 1")
    task1.resume()

    semaphore.wait() // take a token, wait if needed
    print("starting task 2")
    task2.resume()
}

使用信号量,输出就是您所期望的:

starting task 1
Task1 is done
starting task 2
Task2 is done

取出2 semaphore.wait()行,可以看到如何同时发送这两个请求:

starting task 1
starting task 2
Task2 is done
Task1 is done