我在我的应用中进行了多次API调用。我已经创建了函数来包装并执行这些api调用中的每一个#34;即。双子座,coinbase,bitfinex等"这些函数填充一个数组,因此我需要等待所有函数执行才能计算存储在数组中的数据的平均值。我认为最好的方法是使用调度组。但是,dispatchGroup.notify似乎永远不会执行,因此我永远无法计算平均值。我不确定为什么dispatchGroup.notify中的完成块没有执行,因为根据我的阅读,你所需要的只是具有相同匹配的enter()和leave()调用,我有。
override func viewDidLoad() {
super.viewDidLoad()
exchangesTableView.dataSource = self
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
coinbase {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.enter()
gemini {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.enter()
bitfinex {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.enter()
kraken {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.enter()
okcoin {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.enter()
cexio {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.enter()
hitbtc {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.enter()
livecoin {
self.exchangesTableView.reloadData()
dispatchGroup.leave()
}
dispatchGroup.notify(queue: DispatchQueue.main, execute: {
print("inside the average function")
var total: Double = 0.0
var average: Double
for eth in self.exchangesArray{
let ethPrice: Double = Double(eth.price)!
total = total + ethPrice
}
let count: Double = Double(self.exchangesArray.count)
average = total/count
print("The average is: \(average)")
})
以下是我的API包装器:
func coinbase(completion: @escaping () -> Void){
print("Inside the coinbase function")
let url = "https://api.coinbase.com/v2/prices/ETH-USD/spot"
var request = URLRequest(url: URL(string: url)!)
request.setValue("2017-05-19", forHTTPHeaderField: "CB-VERSION")
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
print("inside the task for coinbase")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
if let data = fetchedData["data"] as AnyObject? {
let price = data["amount"] as! String
self.exchangesArray.append(ExchangeObject(name: "Coinbase", price: price))
}
DispatchQueue.main.async {
completion()
}
}
catch{
print("Error 2")
}
}
}
task.resume()
}
func gemini(completion: @escaping () -> Void ){
print("Inside gemini function")
let url = "https://api.gemini.com/v1/pubticker/ethusd"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
print("inside the task for gemini")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
let price = fetchedData["last"] as! String
self.exchangesArray.append(ExchangeObject(name: "Gemini", price: price))
DispatchQueue.main.async {
completion()
}
}
catch{
print("Error")
}
}
}
task.resume()
print("Gemini function completed...exiting")
}
func bitfinex(completion: @escaping () -> Void) {
print("inside the bitfinex function")
let url = "https://api.bitfinex.com/v2/ticker/tETHUSD"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil) {
print("Error")
}
else {
do {
print("inside the task for bitfinex")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
let priceInt = fetchedData[6]
let price = String(describing: priceInt)
self.exchangesArray.append(ExchangeObject(name: "Bitfinex", price: price))
DispatchQueue.main.async {
self.exchangesTableView.reloadData()
}
}
catch {
print("Error")
}
}
}
task.resume()
print("bitfinex function completed...exiting")
}
func kraken(completion: @escaping ()-> Void ){
print("inside the kraken function")
let url = "https://api.kraken.com/0/public/Ticker?pair=ETHUSD"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
print("inside the task for kraken")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
let data = fetchedData["result"] as AnyObject
let xethzusd = data["XETHZUSD"] as AnyObject
let c = xethzusd["c"] as! NSArray
let price = c[0]
self.exchangesArray.append(ExchangeObject(name: "Kraken", price: price as! String))
DispatchQueue.main.async {
completion()
}
}
catch{
print("Error")
}
}
}
task.resume()
}
func okcoin(completion: @escaping () -> Void ){
print("inside the okcoin function")
let url = "https://www.okcoin.com/api/v1/ticker.do?symbol=eth_usd"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
print("inside the task for okcoin")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
let ticker = fetchedData["ticker"] as AnyObject
let price = ticker["last"] as! String
self.exchangesArray.append(ExchangeObject(name: "OKCoin", price: price))
DispatchQueue.main.async {
completion()
}
}
catch{
print("Error")
}
}
}
task.resume()
}
func cexio(completion: @escaping () -> Void ){
print("inside the cexio function")
let url = "https://cex.io/api/last_price/ETH/USD"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
print("inside the task for cexio")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
let price = fetchedData["lprice"] as! String
self.exchangesArray.append(ExchangeObject(name: "CEX.IO", price: price))
DispatchQueue.main.async {
completion()
}
}
catch{
print("Error")
}
}
}
task.resume()
}
func hitbtc(completion: @escaping () -> Void ){
print("inside the hitbtc function")
let url = "https://api.hitbtc.com/api/1/public/ETHUSD/ticker"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
print("inside the task for hitbtc")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
let price = fetchedData["last"] as! String
self.exchangesArray.append(ExchangeObject(name: "HitBTC", price: price))
DispatchQueue.main.async {
completion()
}
}
catch{
print("Error")
}
}
}
task.resume()
}
func livecoin(completion: @escaping () -> Void ){
print("inside the livecoin function")
let url = "https://api.livecoin.net/exchange/ticker?currencyPair=ETH/USD"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if(error != nil){
print("Error")
}
else{
do{
print("inside the task for livecoin")
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
let priceInt = fetchedData["last"]
let price = String(describing: priceInt)
self.exchangesArray.append(ExchangeObject(name: "Livecoin", price: price))
DispatchQueue.main.async {
completion()
}
}
catch{
print("Error")
}
}
}
task.resume()
}