如何在ios中处理多个apis调用?

时间:2016-02-24 03:53:20

标签: ios multithreading

假设在我的视图控制器中,我必须使用NSOperation Queue同时调用3个apis。

我想知道如何使用NSoperation Queue在同一个View Controller中处理多个apis。

1 个答案:

答案 0 :(得分:3)

您可以为每个API调用创建NSOperation,并使用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()
}