2017-07-18 11 views
-5

{"OTP":"5480"}のようなデータをresponseStringという名前の文字列に取得していますが、どうすれば使用できますか?サーバーからデータを解析する方法は?

マイコードはです。

@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に変更したいとします。または、私は文字列の場所に直接Arrayを取得することができます任意の方法はありますか?

+2

なぜこの文字列を配列に変換する必要がありますか?これは1つのOTPしか持っていないので、配列は必要ありません –

+0

何の配列ですか? –

+0

どうすればその文字列からOTP値を取得できますか? –

答えて

0

otpは以下のような辞書から取得できます。データ:あなただけ(とJSONSerialization.jsonObjectであなたの応答データを渡し、あなたはこの使用して、次のコードをachiveすることができ、あなたの応答文字列を解析し、JSON辞書に変換する必要があり

print(responseString["OTP"])

+0

それは投げている間違いです。タイプ文字列には添え字メンバーがありません –

+0

responseStringは辞書型でなければなりません。あなたの 'responseString.result.value!辞書 'にアクセスします。 –

1

「OTP」の値にアクセスするには、オプション:.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 
     } 
関連する問題