Home > Enterprise >  How do I return a DataModel from an Alamofire request once it finished retrieving it's data?
How do I return a DataModel from an Alamofire request once it finished retrieving it's data?

Time:10-08

So I have my main ViewController set up so when I press the search button it performs an alamofire request based on what you type in.

@IBAction func searchButtonPressed(_ sender: Any) {
        if searchField.text != nil {
            let searchedName = searchField.text!
             playerRequestManager.fetchPlayerByName("\(searchedName)")
        }else if searchField.text == nil {
            print("no name entered.")
        }else {
            print("unknown error")
        }
    }

And my requestManager looks like this:

class PlayerRequestManager {
    let baseURL = "https://public-api.tracker.gg/v2/csgo/standard/profile/steam/"
    
    func fetchPlayerByName(_ playerName: String) {
        let headers : HTTPHeaders = [
            "TRN-Api-Key": "my secret api key",
            "Accept": "application/json",
            "Accept-Encoding": "gzip"
        ]
        
        let fullURL = "\(baseURL)\(playerName)"
        
        AF.request("\(fullURL)", headers: headers).response {
            (responseData) in
            guard let data = responseData.data else {return}
            
            do{
                let player = try JSONDecoder().decode(PlayerData.self, from: data)
                
                
                let playerObject = PlayerModel(playerUsername: player.data.platformInfo.platformUserHandle ?? "Error loading data", playerUserID: player.data.platformInfo.platformUserId ?? "Error loading data", avatarURL: player.data.platformInfo.avatarUrl ?? "Error loading data", playerTimePlayed: player.data.segments[0].stats.timePlayed.displayValue ?? "Error loading data", playerKills: player.data.segments[0].stats.kills.displayValue ?? "Error loading data", playerDeaths: player.data.segments[0].stats.deaths.displayValue ?? "Error loading data", playerKD: player.data.segments[0].stats.kd.displayValue ?? "Error loading data", playerDamage: player.data.segments[0].stats.damage.displayValue ?? "Error loading data", playerHeadshots: player.data.segments[0].stats.headshots.displayValue ?? "Error loading data", playerShotsFired: player.data.segments[0].stats.shotsFired.displayValue ?? "Error loading data", playerShotsHit: player.data.segments[0].stats.shotsHit.displayValue ?? "Error loading data", playerShotsAccuracy: player.data.segments[0].stats.shotsAccuracy.displayValue ?? "Error loading data", playerHeadshotPct: player.data.segments[0].stats.headshotPct.displayValue ?? "Error loading data", playerMaychesPlayed: player.data.segments[0].stats.matchesPlayed.displayValue ?? "Error loading data", playerWins: player.data.segments[0].stats.wins.displayValue ?? "Error loading data", playerLosses: player.data.segments[0].stats.losses.displayValue ?? "Error loading data", playerTies: player.data.segments[0].stats.ties.displayValue ?? "Error loading data", playerMVPs: player.data.segments[0].stats.mvp.displayValue ?? "Error loading data", playerMoneyEarned: player.data.segments[0].stats.moneyEarned.displayValue ?? "Error loading data", playerBombsPlanted: player.data.segments[0].stats.bombsPlanted.displayValue ?? "Error loading data", playerBombsDefused: player.data.segments[0].stats.bombsDefused.displayValue ?? "Error loading data", playerHostagesRescued: player.data.segments[0].stats.hostagesRescued.displayValue ?? "Error loading data", playerRoundsPlayed: player.data.segments[0].stats.roundsPlayed.displayValue ?? "Error loading data", playerWLPercentage: player.data.segments[0].stats.wlPercentage.displayValue ?? "Error loading data")
                
                print(playerObject.avatarURL)
            }catch {
                print("error decoding: \(error)")
            }
            
        }
    }
}

How can I "export" (for lack of a better term) my playerObject that I create from a PlayerModel to use in my main Viewcontroller to prepare for a segue to another viewController once I get my PlayerModel set?

CodePudding user response:

How about using a closure? may be a completion block

    class PlayerRequestManager {
        let baseURL = "https://public-api.tracker.gg/v2/csgo/standard/profile/steam/"

        func fetchPlayerByName(_ playerName: String, with completionBlock: @escaping (PlayerModel) -> ()) {
            let headers : HTTPHeaders = [
                "TRN-Api-Key": "my secret api key",
                "Accept": "application/json",
                "Accept-Encoding": "gzip"
            ]

            let fullURL = "\(baseURL)\(playerName)"

            AF.request("\(fullURL)", headers: headers).response {
                (responseData) in
                guard let data = responseData.data else {return}

                do{
                    let player = try JSONDecoder().decode(PlayerData.self, from: data)


                    let playerObject = PlayerModel(playerUsername: player.data.platformInfo.platformUserHandle ?? "Error loading data", playerUserID: player.data.platformInfo.platformUserId ?? "Error loading data", avatarURL: player.data.platformInfo.avatarUrl ?? "Error loading data", playerTimePlayed: player.data.segments[0].stats.timePlayed.displayValue ?? "Error loading data", playerKills: player.data.segments[0].stats.kills.displayValue ?? "Error loading data", playerDeaths: player.data.segments[0].stats.deaths.displayValue ?? "Error loading data", playerKD: player.data.segments[0].stats.kd.displayValue ?? "Error loading data", playerDamage: player.data.segments[0].stats.damage.displayValue ?? "Error loading data", playerHeadshots: player.data.segments[0].stats.headshots.displayValue ?? "Error loading data", playerShotsFired: player.data.segments[0].stats.shotsFired.displayValue ?? "Error loading data", playerShotsHit: player.data.segments[0].stats.shotsHit.displayValue ?? "Error loading data", playerShotsAccuracy: player.data.segments[0].stats.shotsAccuracy.displayValue ?? "Error loading data", playerHeadshotPct: player.data.segments[0].stats.headshotPct.displayValue ?? "Error loading data", playerMaychesPlayed: player.data.segments[0].stats.matchesPlayed.displayValue ?? "Error loading data", playerWins: player.data.segments[0].stats.wins.displayValue ?? "Error loading data", playerLosses: player.data.segments[0].stats.losses.displayValue ?? "Error loading data", playerTies: player.data.segments[0].stats.ties.displayValue ?? "Error loading data", playerMVPs: player.data.segments[0].stats.mvp.displayValue ?? "Error loading data", playerMoneyEarned: player.data.segments[0].stats.moneyEarned.displayValue ?? "Error loading data", playerBombsPlanted: player.data.segments[0].stats.bombsPlanted.displayValue ?? "Error loading data", playerBombsDefused: player.data.segments[0].stats.bombsDefused.displayValue ?? "Error loading data", playerHostagesRescued: player.data.segments[0].stats.hostagesRescued.displayValue ?? "Error loading data", playerRoundsPlayed: player.data.segments[0].stats.roundsPlayed.displayValue ?? "Error loading data", playerWLPercentage: player.data.segments[0].stats.wlPercentage.displayValue ?? "Error loading data")

                    print(playerObject.avatarURL)
                    completionBlock(playerObject)
                }catch {
                    print("error decoding: \(error)")
                }

            }
        }
    }

And finally call it as

playerRequestManager.fetchPlayerByName("\(searchedName)", with: {[weak self] playerObject in
   print(playerObject)
})

CodePudding user response:

class ApiManager {
  static let shared = ApiManager()
  func getProductList( _ playerName: String,completion: @escaping (_ success: PlayerData?, _ error: Error?) -> Void) {
   
    let headers : HTTPHeaders = [
        "TRN-Api-Key": "my secret api key",
        "Accept": "application/json",
        "Accept-Encoding": "gzip"
    ]
    let urlPath = "\(Constants.APP_BACKEND_HOST)/playerName"
    AF.request(urlPath, method: .get,encoding: JSONEncoding.default,headers: headers)
        
        .responseJSON { response in
            switch response.result {
            case .success(let value):
                do {
                    let playerData = try JSONDecoder().decode(PlayerData.self, from: response.data!)
                    print("abc",users)
                    completion(playerData,nil)
                } catch let error as NSError {
                    print("Failed to load: \(error.localizedDescription)")
                    completion(nil,error)
                }
                
                print(value)
            case .failure(let error):
                print(error.localizedDescription)
                completion(nil,error)
            }
        }
    
}

}

and in button function you can access it

@IBAction func searchButtonPressed(_ sender: Any) {
    if searchField.text != nil {
        ApiManager.shared.getProductList(yourparameter) { data, error in
        if let _data = data {
           let playerData = _data
// assign it to playerdata variable
         }
    }else if searchField.text == nil {
        print("no name entered.")
    }else {
        print("unknown error")
    }
}
  • Related