我在名为responseString的字符串中获取{"OTP":"5480"}
之类的数据,我该如何使用它。
我的代码是。
@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()
}
我想将该字符串更改为Array。或者有什么方法可以直接在String的位置获取Array?
答案 0 :(得分:1)
访问" OTP"的价值您需要解析您的响应字符串并将其转换为Json字典,您可以使用以下代码实现此操作,只需在JSONSerialization.jsonObject中传递您的响应数据(使用: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
}
答案 1 :(得分:0)
你可以从下面的字典中获取otp。
print(responseString["OTP"])