Вы можете создать NSOperation
для каждого вызова API и добавить его в NSOperationQueue
с setMaxConcurrentOperationCount = 3
Полный пример:
var operationQueue: NSOperationQueue = NSOperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
operationQueue.maxConcurrentOperationCount = 3;
operationQueue.addOperation(getOperation1())
operationQueue.addOperation(getOperation2())
operationQueue.addOperation(getOperation3())
}
func getOperation1() -> NSOperation {
let operation: NSOperation = NSBlockOperation {() -> Void in
self.callAPI("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98")
}
return operation
}
func getOperation2() -> NSOperation {
let operation: NSOperation = NSBlockOperation {() -> Void in
self.callAPI("http://jsonplaceholder.typicode.com/users")
}
return operation
}
func getOperation3() -> NSOperation {
let operation: NSOperation = NSBlockOperation {() -> Void in
self.callAPI("http://jsonplaceholder.typicode.com/posts?userId=1")
}
return operation
}
func callAPI(urlString:String) {
let URL:NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: URL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if(error != nil) {
print(error!.localizedDescription)
}
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers)
print("Response = \(jsonData)")
} catch {
print("INVALID Response")
}
}
task.resume()
}
все имя функции должны быть одинаковыми или разными? – akshay
@akshay Может быть и то, и другое. Я изменил ответ. Проверьте его. – Vasanth
Еще одна вещь, которую я хочу задать. Может ли быть добавлена зависимость от операции перед добавлением в очередь или мы можем добавить зависимость после добавления операции в очередь? – akshay