简体   繁体   中英

ios - Cannot get data from Alamofire return

I want to get the data from server api using Alamofire call. But after the api function executed, the data return is empty because Swift is asynchronous...

This code is call the server 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)
        }
    }
}

And this code is get data from getAllModels function:

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

I don't know how to use the callback function exactly to bind the data to return model .. Please help!

Use didSet observer of variables. And call api in viewDidload.

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
    }
} 

}

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