I'm trying to make a post request and save the data that comes back but I'm having trouble making the request. This is my code. The url isn't the real one but if I do a regular post on something like postman I do get all the data as a json object with a key pair where the value is an jsonArray.
{
"events": [
{},
{},
]
}
let UrlString = "https://url/data"
let url = URL(string: UrlString)
guard url != nil else {
return
}
let session = URLSession.shared
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let dataTask = session.dataTask(with: request) { (data, response, error) in
//check for errors
if error == nil && data != nil {
//parse JSON
let decoder = JSONDecoder()
do {
let events = try decoder.decode(Event.self, from: data!)
print(events)
}
catch {
print("Error in JSON Parsing")
print(data!)
}
}
}
//make the api call
dataTask.resume()
The thing that happens is the catch error gets printed and the data just prints like 142373 bytes
This is my Events file
import Foundation
struct Event: Codable {
var id:Int = 0
var init_date:String = ""
var end_date:String = ""
var title:String = ""
var description:String?
var color_code:String?
var all_day:Int?
}
I've never done this before, what am I doing wrong?
question from:
https://stackoverflow.com/questions/65905625/make-post-request-urlrequest-in-swift 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…