一旦完成检索数据,我如何从 Alamofire 请求中 return DataModel?
How do I return a DataModel from an Alamofire request once it finished retrieving it's data?
所以我设置了主要 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)")
}
}
}
}
我如何“导出”(因为没有更好的术语)我从 PlayerModel 创建的 playerObject 以在我的主要 Viewcontroller 中使用,以准备与另一个 viewController 的 segue 一次我得到我的 PlayerModel 设置了吗?
使用闭包怎么样?可能是一个完成块
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)
})
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")
}
}
所以我设置了主要 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)")
}
}
}
}
我如何“导出”(因为没有更好的术语)我从 PlayerModel 创建的 playerObject 以在我的主要 Viewcontroller 中使用,以准备与另一个 viewController 的 segue 一次我得到我的 PlayerModel 设置了吗?
使用闭包怎么样?可能是一个完成块
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)
})
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")
}
}