Home > database >  iOS Swift SwiftUI - request json object from POST API
iOS Swift SwiftUI - request json object from POST API

Time:06-29

I'm new to iOS development

I need to make an API request sending some POST values and receiving json object

Ofc I have searched for tutorials and have seen other questions but all the codes I've found are causing all kind of errors.

This is what I've tried last:

func getAppConfig() async {

    guard let url =  URL(string:"https://blasrv.com/appconfig.php")
    else{
        return        }
    let body: [String: String] = ["userid": "420", "device": "ios"]
    let finalBody = try? JSONSerialization.data(withJSONObject: body)
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = finalBody
    
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    URLSession.shared.dataTask(with: request){
        (data, response, error) in
        
        guard let data = data else{
            return
        }
        
        do{
            let jsondata = Data(data)
            
            if let json = try JSONSerialization.jsonObject(with: jsondata, options: []) as? [String: Any] {
                // try to read out a string array
                if let nickname = json["nickname"] as? [String] {
                    print(nickname)
                }
            }
        
            gotConfig = true
            await fetchData()
        }catch{
            print("data not valid")
        }
    }
    .resume()
    
}

It gives:

Cannot pass function of type '(Data?, URLResponse?, Error?) async -> Void' to parameter expecting synchronous function type

on

URLSession.shared.dataTask(with: request)

CodePudding user response:

The problem is that you mix usage of old asynchronous way with new async wait way , you need

class ViewController: UIViewController {

    var gotConfig = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        Task {
            do {
                try await getAppConfig()
            }
            catch {
                print(error)
            }
        }
    }
    func getAppConfig() async throws {

        guard let url =  URL(string:"https://blasrv.com/appconfig.php") else { return }
        let body: [String: String] = ["userid": "420", "device": "ios"]
        let finalBody = try JSONSerialization.data(withJSONObject: body)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = finalBody
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let (data, _) = try await URLSession.shared.data(for: request)
        if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            // try to read out a string array
            if let nickname = json["nickname"] as? [String] {
                print(nickname)
            }
        }
        gotConfig = true
        await fetchData()
    }
    func fetchData() async {
        
    }
}
  • Related