简体   繁体   中英

ios - How to wait api response using Alamofire

I want to ask about Semaphore in Alamofire . 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...

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

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM