RileyDev
RileyDev

Reputation: 2545

Handle Alamofire asynchronous request using SwiftyJSON

I am trying to parse JSON data using SwiftyJSON into an array to use in my TableView. However even though I can successfully request the data and parse it into an array, I cannot return it from the getObjects function as it is done asynchronously. I have tried to use a completion handler, and after following several tutorials it seems I am missing something.

Does anybody know how I can return the array to use in my TableViewController ?

Table View Controller

let objects = [Objects]()

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let urlString = "URLSTRING"
    objects = dataManager.getObjects(urlString)
    print("objects in view controller products array \(objects.count)")
    self.tableView.reloadData
}

Request Functions

class DataManager {

    func requestObjects(_ stringUrl: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void) {
        print("Request Data")
        Alamofire.request(stringUrl, method: .get).validate().responseJSON { response in
            switch response.result {
                case .success(let value):
                    let json = JSON(value)
                    print("responce success")
                    success(json)
                case .failure(let error):
                    print(error)
            } //End of switch statement
        } //End of alamofire request
    }  //End of request function

    func getObjects(_ urlString:String) -> [Object] {
        var objects = [Object]()

        requestObjects(urlString, success: { (JSONResponse) -> Void in
            let json = JSONResponse

            for item in json["items"] {
                let title = item.1["title"].string 
                objects.append(Object(title: title!))
            }
            print("Number of objects = \(objects.count)")
        }) {
            (error) -> Void in
            print(error)
        }
        print(objects)  // Prints empty array
        return objects // Array is empty
    }
}

Upvotes: 2

Views: 320

Answers (1)

FnR
FnR

Reputation: 75

You need to use completionHandler to return data to TableViewController.

func getObjects(completionHandler : @escaping ([Object]) -> (),_ urlString:String) -> [Sneaker] {
    var objects = [Object]()

    requestObjects(urlString, success: { (JSONResponse) -> Void in
        let json = JSONResponse

        for item in json["items"] {
            let title = item.1["title"].string 
            objects.append(Object(title: title!))
        }
       completionHandler(objects)
        print("Number of objects = \(objects.count)")
    }) {
        (error) -> Void in
        print(error)
    }
    print(objects)  // Prints empty array
    return objects // Array is empty
}

}

In your TableViewController

dataManager.getObject(completionHandler: { list in
        self.objects = list
    }, urlString)

There could be some syntax error i didnt test it

Upvotes: 1

Related Questions