I'm trying to use the Swift 4 Codable feature but got stuck in this situation:
struct Message:Codable {
let message: String
let timestamp: String
let latitude: String
let longitude: String}
This is my struct.
guard let url = URL(string:"http://localhost:443/api/message") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
print("POSTED")
let newPost = Message(message: "Hi", timestamp: "1", latitude: "1.1", longitude: "2.2")
print("NewPost:",newPost)
do {
let jsonBody = try JSONEncoder().encode(newPost)
request.httpBody = jsonBody
} catch let err {
print("jsonBody Error: ",err)
}
let session = URLSession.shared
let task = session.dataTask(with: request){ (data,response,err) in
guard let data = data else {return}
do{
let sendPost = try JSONDecoder().decode(Message.self, from: data)
print("sendPost:\(sendPost)")
}catch let err{
print("Session Error: ",err)
}
}
task.resume()
}
And this is the function I use for post request. In the print("NewPost:",newPost), it prints
NewPost: Message(message: "Hi", timestamp: "1", latitude: "1.1", longitude: "2.2")
which looked very identical to other examples I saw, but then there's always a Session Error by catch
Session Error: keyNotFound(DeadDrop.Message.(CodingKeys in _5C64F74710315F52702B56CE54E28C19).message, Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key message (\"message\").", underlyingError: nil))
I just don't understand how this came up! I'm using the exact same struct and it says there's no key for this?! Thanks for any help!
SQLState: 22007 : The string representation of a datetime is not in the acceptable range or is not in the correct format.
As you told that you are getting data
as below :
{"code":"ER_TRUNCATED_WRONG_VALUE","errno":1292,"sqlState":"#22007"}
As per this link , It is expecting different datatype than you are sending.
I suspect the timestamp
you are sending is 1
, and this is not a valid timestamp
.
Try to send timestamp
value as "1508309342"
Other than that your decoding code is fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.