我想使用Alamofire调用从服务器api获取数据。但是在执行api函数之后,数据返回为空,因为Swift是异步的......
此代码调用服务器api:
func getAllModels(completion: @escaping (_ result: [String]?) -> ()) {
var _modelList:[String] = []
let url = BASE_URL + "getAllProductAndModelv2"
Alamofire.request(url, method:.get, parameters: [:], encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
if((response.result.value) != nil) {
let data = NSData(contentsOf: URL(string: url)!)
do {
if let data = data, let json = try JSONSerialization.jsonObject(with: data as Data) as? [String: Any], let models = json["models"] as? [[String:Any]] {
for model in models {
if let name = model["name"] as? String {
_modelList.append(name)
}
}
}
}catch {
print("error")
}
completion(_modelList)
}
case .failure(let error):
print(error)
completion(nil)
}
}
}
此代码是从getAllModels
函数获取数据:
var models:[VirtualObject] = []
RestApiManager().getAllModels(){ (result) -> () in
print("************************************************")
if let result = result {
var array = result as Array
for item in array {
print(item)
models.append(VirtualObject(url: URL(string: item)!)!)
}
}
print("************************************************")
}
print(models)
return models
我不知道如何准确地使用回调函数将数据绑定到return model
..请帮忙!
答案 0 :(得分:1)
使用didSet观察变量。并在viewDidload中调用api。
class ViewController: UIViewController {
var arrModals = [Any]() {
didSet {
print("this call when get all modals from server")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
RestApiManager().getAllModels(){ (result) -> () in
var arrTempModals = [Any]()
if let result = result {
var array = result as Array
for item in array {
print(item)
arrTempModals.append(item)
}
}
self.arrModals = arrTempModals
}
}
}