1

I am studying networking (Alamofire). And in his pet project on Viper architecture. I am making a get request and getting a to-do list from a local server. The data is returned to me successfully. But I just can't figure out how to get them and transfer them to Interactor...

I want my fetchToDos method to return an array. But I keep making mistakes.

func fetchToDos() -> [ToDo]? { // <- My mistake is clearly here

    let request = Session.default.request("http://localhost:3003/")

    request.responseDecodable(of: ToDos.self) { (response) in

        switch response.result {
        case .success(let tasks):
            print("SUCCESS to FETCH JSON: \(tasks)")
        case .failure(let error):
            print("FAILED to FETCH JSON: \(error.localizedDescription)")
        }

    }

}

2 Answers 2

2

you are using an asynchronous function, and so one way to get something out of it when it is finished, is to use a completion handler, something like this: (note you need to do the error checking etc...before you can use this for real)

class ToDoNetworking {

    func fetchToDos(completion: @escaping ([ToDo] -> Void)) { // <- try this
        let request = Session.default.request("http://localhost:3003/")
        request.responseDecodable(of: [ToDos].self) { (response) in

            switch response.result {
            case .success(let tasks):
                print("SUCCESS to FETCH JSON: \(tasks)")
                completion(tasks) // <-- assuming tasks is [ToDo]
            case .failure(let error):
                print("FAILED to FETCH JSON: \(error.localizedDescription)")
                completion([])
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

What is the type of data being returned by the network call? If it's an array of ToDo objects and your ToDo object supports Codable, then it's likely you want:

request.responseDecodable(of: [ToDo].self)

you pass in the type of object that you want to decode, which it sounds like, is an array of ToDo objects, hence [ToDo].self.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.