On my swift I receive a data from my php in json from.
and when I print it displays all directly I would like to know if there is a way to put this data in a table directly or if I have to remove the characters I do not want and cut my string etc..
and here is my code
let parameters = ["id":"\(id)","password":"\(password)"]
var sParams = ""
for (key,value) in parameters{
sParams = key "=" (value as String) "&"
print("\(key),\(value as String)")
}
if !sParams.isEmpty{
sParams = "?" sParams
if sParams.hasSuffix("&"){
sParams.removeLast()
}
urlLink = urlLink sParams
}else{
print("!sParams.isEmpty fail")
}
let serializer = DataResponseSerializer(emptyResponseCodes: [200,204,205])
var request = URLRequest(url : URL(string:urlLink)!)
AF.request(request).uploadProgress{progress in }.response(responseSerializer: serializer){ response in
if response.error == nil {
var responseString: String!
responseString = ""
if response.data != nil {
responseString = String(bytes:response.data!, encoding: .utf8)
}else{
responseString = response.response?.description
}
var dataJson = responseString ?? ""
dataJson = dataJson.replacingOccurrences(of: "\"", with: "")
dataJson = dataJson.replacingOccurrences(of: "password:", with: "")
dataJson = dataJson.replacingOccurrences(of: "email:", with: "")
dataJson = dataJson.replacingOccurrences(of: "{", with: "")
dataJson = dataJson.replacingOccurrences(of: "}", with: "")
dataJson = dataJson.replacingOccurrences(of: "[", with: "")
dataJson = dataJson.replacingOccurrences(of: "]", with: "")
print(dataJson)
var finalData = dataJson.components(separatedBy: ",")
if finalData[0] == id as String && finalData[1] == password as String{
self.present(HomeClientViewController(), animated: true)
}else{
print("erreur dans la conversion")
}
// print(responseString ?? "")
// print(response.response?.statusCode as Any)
var data : NSData!
if let data = data {
//Succeed
let dataLength = data.length
print("Size: \(dataLength) Bytes")
}else{
//print(data)
}
print("response time: \(response.metrics?.taskInterval.duration ?? 0)")
//self.present(HomeClientViewController(), animated: true)
}
}
here is the log how i received the data :
[{"email":"[email protected]","password":"1234"}]
CodePudding user response:
First of all, decode json:
struct User: Decodable {
let email: String
let password: String
}
let jsonFormatter = JSONDecoder()
if let jsonData = jsonString.data(using: .utf8) {
let user = try jsonFormatter.decode([User].self, from: jsonData).first
}
Then, use user item to populate the view you prefer.
CodePudding user response:
thx you for all you answers so i try using a Decodable here is the code i use to properly Decode my JsonData :
struct Login: Decodable {
let email: String
let password: String
}
let jsonObjectData = dataJson!.data(using: .utf8)!
let login = try? JSONDecoder().decode(
Login.self,
from: jsonObjectData
)
print(login!.email as Any)
print(login!.password as Any)