[英]ios - How to wait api response using Alamofire
I want to ask about Semaphore
in Alamofire
. 我想问一下
Alamofire
Semaphore
。 I want the app wait for data from the server return success and continue to execute the code after (synchronous type). 我希望应用程序等待服务器返回的数据成功,并在(同步类型)之后继续执行代码。 I use
semaphore
, but when the api function is called, the app is suspended... 我使用
semaphore
,但是当调用api函数时,该应用已暂停...
This code is call data from server: 此代码是来自服务器的呼叫数据:
func getAllModels() -> [String] {
var _modelList:[String] = []
let url = BASE_URL + "getAllProductAndModelv2"
let semaphore = DispatchSemaphore(value: 0)
Alamofire.request(url, method:.get, parameters: [:], encoding: JSONEncoding.default).responseJSON { response in
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")
}
semaphore.signal()
}
semaphore.wait()
return _modelList
}
And this code is going to get the result: 这段代码将得到结果:
let api = RestApiManager()
var result:[String] = api.getAllModels()
print(result)
How to relsove this issuse? 如何解决这个问题? Thank you
谢谢
Use completion 使用完成
func getAllModels( completion: @escaping ([String] ,Bool) -> Void) {
var modelList:[String] = []
let url = BASE_URL + "getAllProductAndModelv2"
Alamofire.request(url, method:.get, parameters: [:], encoding: JSONEncoding.default).responseJSON { response in
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)
}
}
completion(modelList,true)
}
}catch {
print("error")
completion([],false)
}
}
}
Then call it 然后叫它
self.getAllModels { (data, success) in
if(success)
{
// use data
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.