Unable to add values to Model from JSON in swift

ε祈祈猫儿з 提交于 2020-06-17 08:03:05

问题


I have model like below:

class ProfileModel  : NSObject, NSCoding{

var userId : String!
var userAddresses : [ProfileModelUserAddress]!

init(fromDictionary dictionary: [String:Any]){
    userId = dictionary["userId"] as? String

    userAddresses = [ProfileModelUserAddress]()
    if let userAddressesArray = dictionary["userAddresses"] as? [[String:Any]]{
        for dic in userAddressesArray{
            let value = ProfileModelUserAddress(fromDictionary: dic)
            userAddresses.append(value)
        }
}}

func toDictionary() -> [String:Any]
{
    var dictionary = [String:Any]()
    if userId != nil{
        dictionary["userId"] = userId
    }
    if userAddresses != nil{
        var dictionaryElements = [[String:Any]]()
        for userAddressesElement in userAddresses {
            dictionaryElements.append(userAddressesElement.toDictionary())
        }
        dictionary["userAddresses"] = dictionaryElements
    }
    return dictionary
}

@objc required init(coder aDecoder: NSCoder)
{
    userId = aDecoder.decodeObject(forKey: "userId") as? String
    userAddresses = aDecoder.decodeObject(forKey: "userAddresses") as? [ProfileModelUserAddress]
}
@objc func encode(with aCoder: NSCoder)
{
    if userId != nil{
        aCoder.encode(userId, forKey: "userId")
    }
    if userAddresses != nil{
        aCoder.encode(userAddresses, forKey: "userAddresses")
    }
    }
}

In ProfileViewController i am adding values to Model with /getprofile/ api : for first time all model values coming correctly

and i am adding new address in NewZoomAddressViewController with /saveaddress/ api : in this api with new address i am getting addressID.. when i send address from NewZoomAddressViewController to ProfileViewController tableview here all the time with new address i am getting the old adress(from getprofile) adding to tableview why?

for eg: first time one address if i add new address then it should be two adresse but i am getting three adress, please do help here with the code

class ProfileViewController: UIViewController {

var userModel : ProfileModel?
var addressArray = [String]()

override func viewWillAppear(_ animated: Bool) {
 self.navigationController?.navigationBar.isHidden=true
 getUserProfile()
 }
func getUserProfile() {
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
    do {
        let jsonObject  = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
        self.userModel = ProfileModel.init(fromDictionary: jsonObject)

        if (self.userModel?.userId) != nil {

            DispatchQueue.main.async {
                self.updateUserDetails()
                self.addressTableview.reloadData()
            }
        }
    }
 }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return userModel?.userAddresses.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell: AddresCell = tableView.dequeueReusableCell(withIdentifier: "AddresCell") as! AddresCell
    let addr = userModel?.userAddresses![indexPath.row]

    if addr?.addressId != nil{

                  cell.name.text    = addr?.addressName
                  let street = addr?.streetName
                  let colony = addr?.colony
                  let city   = addr?.city
                   let pincode = addr?.pincode
                    cell.address.text = street! + "," + colony! + "," + city! + "," + pincode!
                    KeychainWrapper.standard.set(cell.address.text ?? "", forKey: "ADDRESS")
    }
        return cell
    }

NewZoomAddressViewController code: like below i am sending new address to profileviewcontroller. In this saveaddAddressService i am getting addressId

class NewZoomAddressViewController: UIViewController {


 @IBAction func confirmBtn(_ sender: Any) {
          for controller in navigationController?.viewControllers ?? [] {
               if let listController =  controller as? ProfileViewController {

                   let string = "\(streetNumber ?? "") \(streetName ?? "") \(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")"
                 saveaddAddressService()
                   listController.addressArray.append(string)
                 navigationController?.popToViewController(controller, animated: true)
                   return
               }

            else if let listController =  controller as? Add_EditAddressViewController {

                 let string = "\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")"
                 listController.addressArray.append(string)
                 saveaddAddressService()
                 navigationController?.popToViewController(controller, animated: true)
                 return
             }
           }
  }

 func saveaddAddressService(){

 let parameters: [String: Any] = [
                     "pincode": zipName,
                     "city": localityName,
                     "streetName": sublocalityName,
                     "colony": "",

                 ]
                 //some JSON code.....
             let httpResponse = response as? HTTPURLResponse
             if httpResponse!.statusCode == 200 {
                 do {
                     let jsonObject  = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String: Any]
                     self.addAddrsID = jsonObject["addressId"] as! String
                     UserDefaults.standard.set(self.addAddrsID, forKey: "addAddress")

                 } catch { print(error.localizedDescription) }
         }
     })
     dataTask.resume()
 }

Please any one don't mind, its may be lenghty post, but i am a Jr developer

how to add one getprofile adress and if i add new adress then only new adress need to add in tableview in profileviewcontroller

please help me with code.

来源:https://stackoverflow.com/questions/62390626/unable-to-add-values-to-model-from-json-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!