skip to Main Content

I was trying to wrap Alamofire with async, but the answers that I found couldn’t help me, but after finding the solution, I thought that I should help some one with this same problem.

2

Answers


  1. Chosen as BEST ANSWER

    Following a very decoupled MVVM project, my DataLayer was outside from the ViewModel Layer, so I couldn't let the AF.request handler the Diffable direct. So my solution was wraping the @escaping with withCheckedContinuation

    In DataLayer.swift:

    func fetchRequests() async -> [MyModel] {
            await withCheckedContinuation{ continuation in
                downloadJson{ models in
                    continuation.resume(returning: models)
            }
        }
    }
    
    private func downloadJson(completion: @escaping ([MyModel]) -> Void){
            let url = "https://......"
            AF.request(url).responseDecodable(of: [MyModel].self){ response in
                guard let models = response.value else {return}
                completion(models)
            }
        }
    

    ModelModule.swift:

    var data: [MyModel]
    
    func loadData() async {
        data = await dataLayer.fetchRequests()
    }
    

    Finally the ViewModel.swift:

    func configure(dataSource: AnyDiffableDataSource<MySection, MyModelItem>) {
            self.dataSource = dataSource
            
            Task {
                await modelModule.loadData()
                dataSource.create(sections: [.main], animated: true)
                updateDateSource(animated: true)
                //... rest of the configuration
            }
        }
    

  2. There’s no need to wrap Alamofire for async / await, it already offers a native version of that API.

    let response = await AF.request(...).serializingDecodable(<YourType>.self)
    

    You can also await .result and try await .value on the above to access the parts you need.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search