Итак, у меня настроен основной ViewController, поэтому, когда я нажимаю кнопку поиска, он выполняет запрос alamofire в зависимости от того, что вы вводите.

@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")
        }
    }

И мой requestManager выглядит так:

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)")
            }
            
        }
    }
}

Как я могу «экспортировать» (из-за отсутствия лучшего термина) мой playerObject, который я создаю из PlayerModel, для использования в моем основном Viewcontroller, чтобы подготовиться к переходу на другой viewController после того, как я получу свой PlayerModel?

0
slimeforest 8 Окт 2021 в 09:33

2 ответа

Лучший ответ

Как насчет закрытия? может быть блоком завершения

    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)")
                }

            }
        }
    }

И, наконец, назовите это как

playerRequestManager.fetchPlayerByName("\(searchedName)", with: {[weak self] playerObject in
   print(playerObject)
})
0
Sandeep Bhandari 8 Окт 2021 в 06:45
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)
            }
        }
    
}

}

И в функции кнопки вы можете получить к ней доступ

@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")
    }
}
0
Zeeshan Ahmed 8 Окт 2021 в 06:53