-2

I got this json data from PHP API. but how to convert it to show in app. Actually it works fine before adding circle name and id but when this api returns circle name and it it does not work. Please help. Thanks in advance.

JSON:["data": <__NSArrayM 0x60800025bed0>(
{
    Email = "ganesh@gmail.com";
    ID = 104;
    Name = archana;
    Phone = "( 91)9111111110";
    status = 1;
    timeinterval = 15;
    userpic = "";
},
{
    circleName = "<null>";
    circleid = 155;
}
)
]

below is my code.

 let configuration = URLSessionConfiguration.default
                let session = URLSession(configuration: configuration)

                let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
                    do
                    {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String:Any]
                        print("JSON:\(json)")
                        if let data = json["data"] as? [[String:String]]
                        {
                            self.stopIndicator()
                            print("DATA:\(data)")
                            if let errorString = data.first?["Error"]
                            {
                                print("Error: \(errorString)")
                                if (errorString == "Invalid Email or Password")
                                {
                                    // Perform Operation in Main thread
                                    OperationQueue.main.addOperation
                                        {
                                            let alertController = UIAlertController(title: "Invalid Email or Password", message: "Your Email or password is Invalid. Please Enter Correct Email or Pasword.", preferredStyle: UIAlertControllerStyle.alert)
                                            alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {(_action) -> Void in
                                                _ = self.navigationController?.popViewController(animated: false)

                                            }))
                                            self.present(alertController, animated: true, completion: nil)
                                        }
                                }
                            }

                            else if let UserArray = (json as AnyObject).object(forKey: "data") as? NSArray
                            {
                                 for UserDic in UserArray
                                 {
                                var Email:String
                                var ID:String
                                var Name:String
                                var Phone:String
                                var status:String
                                var timeinterval:String
                                var userpic:String

                                Email = ((UserDic as AnyObject).object(forKey: "Email") as? String)!
                                ID = ((UserDic as AnyObject).object(forKey: "ID") as? String)!
                                Name = ((UserDic as AnyObject).object(forKey: "Name") as? String)!
                                Phone = ((UserDic as AnyObject).object(forKey: "Phone") as? String)! 
                                status = ((UserDic as AnyObject).object(forKey: "status") as? String)!
                                timeinterval = ((UserDic as AnyObject).object(forKey: "timeinterval") as? String)!
                                userpic = ((UserDic as AnyObject).object(forKey: "userpic") as? String)!

                                let userModel = UserDetailsArray(UserEmail: Email, UserId: ID, UserName: Name, UserPhone: Phone, UserStatus: status, TimeInterVal: timeinterval, UserPic: userpic)

1 Answers1

1

You have got an array of dictionaries and each dictionary has different structure while parsing.

Why am I saying this?

   json = [dictionaryOne, dictionaryTwo...]
   dictionaryOne = ["Email": "" , "ID": ....]
   dictionaryTwo = ["cicileName": nil, "circleid": ""....]

Now when you are parsing the array,

   for UserDic in UserArray {
       // here initialising the variables
   }

You are not making sure that the second structure dictionary would come and that's why you are getting error.

The simple solution would be to have a check i.e.

  for UserDic in UserArray {
      if let circleName = (UserDic as AnyObject).object(forKey: "circleid") as? String {
          // do not parse if you don't need the data of this dict and continue
          continue;
      } else {
         // parse the other dictionary which has Email, ID etc
         var Email: String
         var ID:String
         .
         .
         .
      }
  }

If you want to store both the dictionary then define similar variables and store inside the if block.

Rahul
  • 2,056
  • 1
  • 21
  • 37
  • if CircleName = "Family" then what is the solution – Archana SIngh May 23 '17 at 06:30
  • @ArchanaSIngh I have provided you the solution. You are looping on two different dictionaries and each has a different structure and so to parse them you need two sets of logic. – Rahul May 23 '17 at 06:37
  • i did not get the result i used if let circleid = ((UserDic as AnyObject).object(forKey: "circleid") as? String)! and the error is "Initializer for conditional binding must have Optional type, not 'String'" – Archana SIngh May 23 '17 at 07:08
  • Because @ArchanaSIngh this line is not an optional `((UserDic as AnyObject).object(forKey: "circleid") as? String)!`. You can use this line `(UserDic as? [String: AnyObject]).object(forKey: "circleid") as? String` – Rahul May 23 '17 at 07:29
  • where should i write this line – Archana SIngh May 23 '17 at 07:54
  • Thanks it Works fine.@Rahul – Archana SIngh May 23 '17 at 08:57