我正在尝试在模型对象中获得响应,但是面临一个问题,即它仅向我显示响应的第一项,这是我的代码,
func getUserBalanceAPI()
{
APIService.getUserBalance{ (responseObject) in
if (responseObject?.status)! {
self.balanceArray.removeAll()
let user = UserCompleteBalance(JSON: (responseObject?.data as! [[String : Any]]).first!)
self.balanceArray.append(user!)
//Reload Collection View
self.currencyCVC.reloadData()
}
else if !(responseObject?.status)! {
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}
}
如何获取数组中的所有项目?这是我的回应,
"responseBody": {
"data": [
{
"auction_deposit": 4083.63,
"currencyCode": "USD",
"userCurrencyId": 1,
"availableBalance": 64555.1,
"currentBalance": 68638.73
},
{
"auction_deposit": 0.0,
"currencyCode": "AED",
"userCurrencyId": 2,
"availableBalance": 198000.0,
"currentBalance": 198000.0
},
{
"auction_deposit": 0.0,
"currencyCode": "EUR",
"userCurrencyId": 3,
"availableBalance": 50000.0,
"currentBalance": 50000.0
}
]
}
这是我的模型课,
class UserCompleteBalance : Mappable {
var auctionDeposit : Int?
var availableBalance : Int?
var currencyCode : Int?
var currentBalance : Int?
var userCurrencyId : Int?
required init?(map: Map) {
}
func mapping(map: Map) {
auctionDeposit <- map["auction_deposit"]
currencyCode <- map["currencyCode"]
userCurrencyId <- map["userCurrencyId"]
availableBalance <- map["availableBalance"]
currentBalance <- map["currentBalance"]
}
}
现在我要在其中存储所有响应。
答案 0 :(得分:1)
let user = UserCompleteBalance(JSON: (responseObject?.data as! [[String : Any]]).first!)
self.balanceArray.append(user!)
以上各行应循环通过responseObject.data
中的所有对象
您的getUserBalanceAPI
函数应该是
APIService.getUserBalance{ (responseObject) in
if (responseObject?.status)! {
self.balanceArray.removeAll()
if let jsonObjects = responseObject?.data as? [[String : Any]] {
for jsonObject in jsonObjects {
if let user = UserCompleteBalance(JSON: jsonObject) {
self.balanceArray.append(user)
}
}
}
//Reload Collection View
self.currencyCVC.reloadData()
} else if !(responseObject?.status)! {
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}
}
答案 1 :(得分:1)
您的问题与以下事实有关:您仅在字典数组上获得了第一本字典,因此您需要遍历字典数组以在UserCompleteBalance
模型上转换它们中的每一个
您需要在封闭中使用[weak self]和strongSelf以避免保留周期
尝试使用此代码
func getUserBalanceAPI()
{
APIService.getUserBalance{ [weak self] (responseObject) in
guard let strongSelf = self else {
return
}
if (responseObject?.status)! {
strongSelf.balanceArray.removeAll()
if let usersDataArray = responseObject?.data as? [[String : Any]] {
for userData in usersDataArray {
strongSelf.balanceArray.append(UserCompleteBalance(JSON:userData))
}
}
//Reload Collection View
strongSelf.currencyCVC.reloadData()
}
else if !(responseObject?.status)! {
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}
}