-2

I am fetching the data from the JSON. I want to know how I can fetch the signal value. because as per the signal all the code will work.

["status": 200, "data": {"in_time" = "12:00 PM"; "out_time" = ""; signal = 01;}, "Message": Enable out time]

this is code which I am using: Here is all the data which I am using to get the json response

    let parameters = ["emp_id": self.att_emp_id]
    var request = URLRequest(url : url!)
    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject:parameters, options: [])
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let session = URLSession.shared
    session.dataTask(with: request, completionHandler: { (data, response, error) in
        if let data = data {
            do {
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
                if let json = json {
                    print("HERE SHOULD BE YOUR JSON viewdidAppear\(json)")
                    //var datas = [String:AnyObject]()
                    let status = json["status"] as? String
                    if let datas = json["data"] as? [String:AnyObject]  , let in_time_Str = datas["in_time"] as? String, let out_time_Str = datas["out_time"] as? String , let grace_Str = datas["grace"] as? String , let signal_Str = datas["signal"] as? String
                    {
                        self.server_in_time = in_time_Str
                        self.server_out_time = out_time_Str
                        self.grace_str_time = grace_Str
                        self.sig_str = signal_Str
                    }
                    print("Signal : \(String(describing: self.sig_str))")
                    if status == "200" {
                        if self.server_in_time != "" {
                            print("Here is attendance IN TIME : \(self.server_in_time)")
                        }
                        if self.server_out_time != "" {
                            print("Here is attendance OUT TIME : \(self.server_out_time)")
                        }
                        if self.sig_str == "10" {
                            DispatchQueue.main.async {
                                self.out_time_button.isEnabled = false
                            }
                        } else if self.sig_str == "01" {
                            DispatchQueue.main.async {
                                self.inTimeTextField.text = self.server_in_time
                                self.in_time_button.isEnabled = false
                                self.out_time_button.isEnabled = true
                            }
                        } else if self.sig_str == "00" {
                            DispatchQueue.main.async {
                                self.inTimeTextField.text = self.server_in_time
                                self.outTimeTextField.text = self.server_out_time
                                self.in_time_button.isEnabled = false
                                self.out_time_button.isEnabled = false
                            }
                        }
                    } else {
                        print("Error : \(String(describing: error))")
                    }
                }
            }
        } else {
            print("Error \(String(describing: error?.localizedDescription))")
        }
    }).resume()
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sandesh Zote
  • 23
  • 1
  • 8

1 Answers1

1

Ouch, poor you, the giant ant has badly hit you with the curse of the evil JSONSerialization (pardon the cheap NetHack rip off). This looks easy at first, but you will have to deal with the curse (cast) of the evil Optional/Any. You will be much better off (even concerning error messages) if you go with the Codable protocol. This will boil down to the following:

import Cocoa

let jsonData = """
{"status": 200,
   "data": {
        "in_time": "12:00 PM",
        "out_time": "",
        "signal": "01",
    },
"Message": "Enable out time"
}
""".data(using: .utf8)!

struct TimeData: Codable {
    let inTime: String
    let outTime: String
    let signal: String

    enum CodingKeys : String,CodingKey {
        case inTime = "in_time"
        case outTime = "out_time"
        case signal
    }
}

struct TimeResult: Codable {
    let status: Int
    let data: TimeData
    let message: String
    enum CodingKeys : String,CodingKey {
        case status, data
        case message = "Message"
    }
}

do {
    let timeData = try JSONDecoder().decode(TimeResult.self, from:jsonData)
    print(timeData)
} catch {
    print(error)
}

As you probably notice I had to modify quite a few things with your "JSON" to make this compile.

  1. Your top level structure is a hash, not an array, i.e. your JSON-string should start with a { instead of an [ and finish with a } in return.
  2. The values in you data hash seem to be separated with = instead of :, this won't be parsed by a standard compliant parser
  3. The key:value pairs in your data hash are separated with ; instead of ,, this won't be parsed by a standard compliant parser
  4. The key part of your signal line is not surrounded by " to indicate a String value this won't be ... (you know the drill by now)
  5. The value part of your signal line is not surrounded by " which lets the parser guess it to be a number which results in an illegal condition ("Number with leading zero around character 103.").

All these errors (except maybe the first one) are fairly easy to spot if you use a JSONDecoder and the appropriate Codable protocol for you model. They are however rather hard to spot given the unfortunate JSONSerialization which will try (too) hard to make sense of whatever you throw at it ...

And for the record:

print(timeData.data.signal)

will beautifully access your signal in a really straightforward way, even without the excessive use of if let=... bindings.

Addition

After rereading the above I realised, that your "JSON" might have resulted from the way you printed your data in the first place. Try using

print(String(data:data, encoding:.utf8)!)

to find out what your JSON actually looks like.

Patru
  • 4,481
  • 2
  • 32
  • 42