我的场景是解析json,并在表视图上显示该信息。尽管可以解析json scusess,但可以在控制台上正确打印测试,但是我仍然无法将该信息添加到我真正想要的item对象中。
我尝试了很多方法,但是仍然困惑为什么我不能。
首先,使用func loadProductListInfo(),我得到以下json:
"success": true,
"result": {
"data": [
{
"id": 5,
"name": "ERFSDSSD"
},
{
"id": 13,
"name": "Messi"
},
{
"id": 12,
"name": "DonadoNi_O"
},
],
"next_index": 0
}
}
在该函数中,我还调用func loadItemInfo(id:Int,item:Item)来获取带有json的Item详细信息,如下所示,并打印出来进行测试。
"success": true,
"result": {
"next_index": 0,
"data": [
{
"product_name": "AABBCC",
"brand_name": "EVELYNE",
"code": "DDEERR",
"retail_price": 434632,
"import_price": null,
"properties": [
{
"caption": "Type 1",
"value": "Coats"
}
],
"inventory": [
{
"quantity": 4,
"store": "BBB",
"id": 15,
"booking": [
{
"booking_quantity": 4,
"booking_staff": "KKK"
}
]
},
{
"quantity": 98,
"store": "AAA",
"id": 13,
"booking": [
{
"booking_quantity": 5,
"booking_staff": "SSSS"
}
]
},
{
"quantity": 2,
"store": "CCC",
"id": 14,
"booking": [
{
"booking_quantity": 1,
"booking_staff": "NNNN"
}
]
}
],
"image": null
}
]
}
}
json解析结果似乎正确,但是问题是在调用loadProductListInfo()之后,此行self.item = item
的结果不再起作用。
下面是我在“搜索”视图控制器中的代码:
class SearchVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
//outlets
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
//variables
var isSearching = false
var products = [Product]()
var item = Item()
var items = [Item]()
var product = Product()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
loadProductListInfo()
tableView.reloadData()
}
func loadProductListInfo() {
let parameters = [
"method": "get_list",
"param": [
"list_name": "brand",
"keyword2": "k",
"start_index": 0,
"page_size": 100
]
] as [String : Any]
let headers = [
"Content-Type": "application/json",
"User-Agent": "PostmanRuntime/7.11.0",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "3792a1a9-c3eb-449d-9c5d-22ff15e77bbc,75a0a1e1-963c-4937-a4af-42e76b863870",
"Host": "123.4xx.x.y",
"cookie": "ci_session=i3j4o9q0n7bd1s6015jurlkr0bfn596d",
"accept-encoding": "gzip, deflate",
"content-length": "160",
"Connection": "keep-alive",
"cache-control": "no-cache"
]
do {
let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "http://xxx.xxx.x.x/xxx/api/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print("Error get jsonData: \(error)")
} else {
let httpResponse = response as? HTTPURLResponse
print("Đây là httpResponse cua Get List Box: \(httpResponse)")
do {
if let convertedJsonDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print(convertedJsonDict)
if let result = convertedJsonDict["result"] as? [String:Any] {
print("Result day ne: \(result)")
if let dataArr: NSArray = result["data"] as? NSArray {
for x in dataArr {
if let productInfo = x as? [String: Any] {
guard let productId = productInfo["id"] as? Int else {return}
guard let productName = productInfo["name"] as? String else {return}
let productInstance = Product(id: productId, name: productName)
self.products.append(productInstance)
print("Day la product list: \(productInstance.id, productInstance.name)")
/*
print("Items Arr: \(self.items), \(self.items.count)")
for x in self.items {
print("Item ID in Arr: \(x.itemName)")
}
*/
}
}
print("Products list: \(self.products.count)")
for eachProduct in self.products {
self.loadItemInfo(id: eachProduct.id, item: self.item)
//properies of selft.item is null here.
self.items.append(self.item)
}
print("Items Arr length: \(self.items.count)")
}
}
}
} catch let err as NSError {
print("Co Error nay: \(err)")
}
}
})
dataTask.resume()
} catch let err as NSError {
print("Có error: \(err)")
}
}
func loadItemInfo(id: Int, item: Item) {
let headers = [
"Content-Type": "application/json",
"User-Agent": "PostmanRuntime/7.11.0",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "37f3517d-e849-48e4-af20-134b7cc61322,31f79da6-e3fa-49a1-991f-a20837e9179e",
"Host": "xxx.xxx.x.x",
"cookie": "ci_session=i3j4o9q0n7bd1s6015jurlkr0bfn596d",
"accept-encoding": "gzip, deflate",
"content-length": "149",
"Connection": "keep-alive",
"cache-control": "no-cache"
]
let parameters = [
"method": "get_itemDetails",
"param": [
"id": id,
"brand_name1": "",
"product_code1": "",
"product_name1": ""
]
] as [String : Any]
do {
let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "http://xxx.xxx.x.x/xxx/api/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print("Get Item httpResponse la : \(httpResponse)")
do {
if let JsonDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print("\(JsonDict)")
if let result = JsonDict["result"] as? [String:Any] {
print("Result Get Item day ne: \(result)")
if let dataArr: NSArray = result["data"] as? NSArray {
print("Vo duoc data array")
let testArr = dataArr[0] as! NSDictionary
item.id = id //gán lại id product cho itemId được input
guard let product_name = testArr["product_name"] as? String else {return}
print("product_name: \(product_name)")
item.itemName = product_name
guard let retail_price = testArr["retail_price"] as? Int else {return}
print("retail_price: \(retail_price)")
item.giaBanLe = retail_price
if let inVen:NSArray = testArr["inventory"] as? NSArray {
print("Khai bao inVen la Arr: \(inVen)")
let inventoryArr = inVen[0] as! NSDictionary
print("inventoryArr.count: \(inventoryArr.count)")
guard let quantity = inventoryArr["quantity"] as? Int else {return}
print("quantity: \(quantity)")
//phai get quantity tai day
item.soLuong = quantity
guard let store = inventoryArr["store"] as? String else {return}
print("store: \(store)")
//phai get store nay
if let bookingArr:NSArray = inventoryArr["booking"] as! NSArray, bookingArr.count > 0 {
print("Khai bao bookingArr la Array")
print(bookingArr)
for i in bookingArr {
if let bookingArrContent = i as? [String: Any] {
guard let booking_quantity = bookingArrContent["booking_quantity"] as? Int else {return}
print("booking_quantity: \(booking_quantity)")
//phai get booking_quantity
item.booking = booking_quantity
guard let booking_staff = bookingArrContent["booking_staff"] as? String else {return}
print("booking_staff: \(booking_staff)")
//phai get booking_staff
}
}
}else {
var booking_quantity = 0
var booking_staff = ""
print("booking_quantity: \(booking_quantity)")
//phai get booking_quantity
item.booking = booking_quantity
print("booking_staff: \(booking_staff)")
//phai get booking_staff
}
guard let image = testArr["image"] as? String else {return}
print("image: \(image)")
item.imgURL = image
}
}
}
}
/*
self.item = item
print("self.item Name: \(self.item.itemName)")
print("self.item Booking Quantity: \(self.item.booking)")
print("self.item Img: \(self.item.imgURL)")
print("self.item ID: \(self.item.id)")
*/
} catch let err as NSError {
print("Co Error nay: \(err)")
}
self.item = item
print("self.item Name: \(self.item.itemName)")
print("self.item Booking Quantity: \(self.item.booking)")
print("self.item Img: \(self.item.imgURL)")
print("self.item ID: \(self.item.id)")
}
})
dataTask.resume()
/*
self.item = item
print("self.item Name: \(self.item.itemName)")
print("self.item Booking Quantity: \(self.item.booking)")
print("self.item Img: \(self.item.imgURL)")
print("self.item ID: \(self.item.id)")
*/
} catch let err as NSError {
print("Error roi :\(err)")
}
/*
self.item = item
print("self.item Name: \(self.item.itemName)")
print("self.item Booking Quantity: \(self.item.booking)")
print("self.item Img: \(self.item.imgURL)")
print("self.item ID: \(self.item.id)")
*/
}
func numberOfSections(in tableView: UITableView) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as? CustomCellVC {
//cell.configureItemCell(item: item)
item = items[indexPath.row]
cell.configureItemCell(item: item)
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
我的物品分类:
class Item {
var id: Int
var itemName: String
var soLuong: Int
var giaBanLe: Int
var imgURL: String
var booking: Int
init(id: Int = 0, itemName: String = "", soLuong: Int = 0, giaBanLe: Int = 0, imgURL: String = "", booking: Int = 0) {
self.id = id
self.itemName = itemName
self.soLuong = soLuong
self.giaBanLe = giaBanLe
self.imgURL = imgURL
self.booking = booking
}
}
在此处理中:
for x in self.items {
print("Item ID in Arr: \(x.itemName)")
}
*/
}
}
print("Products list: \(self.products.count)")
for eachProduct in self.products {
self.loadItemInfo(id: eachProduct.id, item: self.item)
//properies of selft.item is null here.
self.items.append(self.item)
}
print("Items Arr length: \(self.items.count)")
我有products.count
= 13(例如)
但是当我计算这行print("self.item Name: \(self.item.itemName)")
时,结果仅为:6。
我的预期:也是13岁。我应该如何修改以达到预期?
请帮助我存储项目的属性并在表格视图中显示。现在我的表格视图仍为空白,什么也不显示,请指出该怎么做?
先感谢您。 (注意:我修改了一些json值的时间不太长。)