-5

I am getting data like {"OTP":"5480"} in a string named responseString, How can I uset it.

My Code is.

@IBAction func signupButton() {
    var request = URLRequest(url: URL(string:"http://122.166.215.8:8090/RESTMVC/validateMobileNumber")!)
    request.httpMethod = "POST"

    let mobileNumberString : String = self.mobileNumberTextfield.text!

    let postString = ["mobileNumber":mobileNumberString]

    request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }
        let responseString = String(data: data, encoding: .utf8)
        var recived = [UInt8]()
        recived.append(contentsOf: data)
        print(responseString!)
        DispatchQueue.main.async(execute: {
            self.performSegue(withIdentifier: "OTPView", sender: nil)
        });
    }
    task.resume()
}

and I want to change that string into Array. Or is there any way in which I can get Array directly on the place of String?

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

1

To access value of "OTP" you need to parse your response string and convert it in Json dictionary you can achive this using following code, just pass your response data in JSONSerialization.jsonObject(with: data, options: .allowFragments)

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String, Any>

            if let otpValue = json["OTP"] {
                print("Otp value : \(otpValue)")
            }

        } catch {
            // Handle Exception
        }
0

You can get otp from dictionary like below.

print(responseString["OTP"])

Sanjay Shah
  • 502
  • 2
  • 13