我有一些助手对API进行Alamofire getRequest,然后填充一些我需要的数组,以便下一个ViewController显示正确的信息。我在这里在appDelegate中调用请求:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
CGCoins.shared.getData { (arr) in
}
CGExchange.shared.getData { (arr) in
}
CGPrices.shared.getData { (arr) in
}
但是它们需要一些时间才能完成,并且在加载ViewController之前会导致崩溃或空标签等。这是助手在内部的外观:
import Foundation
import Alamofire
import SwiftyJSON
class CGCoins {
static let shared = CGCoins()
var ids: [String] = []
var symbols: [String] = []
var names: [String] = []
var coinDictionary: [String : String] = [:]
var defaultCurrency = UserDefaults.standard.string(forKey: "DefaultCurrency")
func getData(completion:@escaping(_ arr:[Type])->()) {
/// alamofire / urlsession request
let url = "https://api.coingecko.com/api/v3/coins/list"
Alamofire.request(url).responseJSON { response in
switch response.result {
case .failure(let error):
// Do whatever here
return
case .success(let data):
// First make sure you got back a dictionary if that's what you expect
let responseJSON = JSON(response.result.value!)
if responseJSON.count != 0 {
//do whatever you want with your object json
parse(json: responseJSON)
}
}
}
/// after finish completion(arr)
func parse(json: JSON) {
for result in json[].arrayValue {
let id = result["id"].stringValue
let symbol = result["symbol"].stringValue
let name = result["name"].stringValue
ids.append(id)
symbols.append(symbol)
names.append(name)
for (index, element) in ids.enumerated() {
coinDictionary[element] = symbols[index]
}
}
}
}
}
pageViewController和ViewController使用此数据。我尝试在启动后创建第二个启动屏幕并在此处调用get请求,但是如何使它在get请求完成之前不将其推送到pageViewController?