Проблема возникает после разбора JSON от почтальона - PullRequest
0 голосов
/ 15 мая 2019

Мой сценарий разбирает json и показывает эту информацию в табличном представлении. Несмотря на синтаксический анализ json scusess, правильно распечатайте тест на консоли, но я все еще не могу добавить эту информацию к моему объекту item, который мне действительно нужен.

Я пробовал много способов, но все еще путаю, почему не могу.

Во-первых, с помощью функции 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), чтобы получить детали Item с помощью json, как показано ниже, и распечатать для проверки.

    "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 (ex) Но когда я считаю эту строку, результат print("self.item Name: \(self.item.itemName)"): 6. Мой ожидаемый: 13 тоже. Как я должен изменить, чтобы получить это ожидаемое? Пожалуйста, помогите мне сохранить свойства элемента и показать в виде таблицы. Теперь мой табличный вид все еще пуст, не показывать ничего, пожалуйста, укажите, как это сделать? Заранее спасибо. (Примечание: я изменил некоторые значения JSON не слишком долго.)

...