Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

Make post request URLRequest in Swift

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...