Search code examples
swiftalamofire

Returning parsed JSON data using Alamofire?


Hello new to Swift and Alamofire,

The issue i'm having is when I call this fetchAllUsers() the code will return the empty users array and after it's done executing it will go inside the AF.request closure and execute the rest.

I've done some research and I was wondering is this is caused by Alamofire being an Async function.

Any suggestions?

func fetchAllUsers() -> [User] {
    var users = [User]()
    
    let allUsersUrl = baseUrl + "users/"
    
    if let url = URL(string: allUsersUrl) {
        AF.request(url).response { response in
            if let data = response.data {
                users = self.parse(json: data)
            }
        }
    }
    return users        
}

Solution

  • You need to handle the asynchrony in some way. This this means passing a completion handler for the types you need. Other times it means you wrap it in other async structures, like promises or a publisher (which Alamofire also provides).

    In you case, I'd suggest making your User type Decodable and allow Alamofire to do the decoding for you.

    func fetchAllUsers(completionHandler: @escaping ([User]) -> Void) {
        let allUsersUrl = baseUrl + "users/"
        
        if let url = URL(string: allUsersUrl) {
            AF.request(url).responseDecodable(of: [User].self) { response in
                if let users = response.value {
                    completionHandler(users)
                }
            }
        }
    }
    

    However, I would suggest returning the full Result from the response rather than just the [User] value, otherwise you'll miss any errors that occur.