makeAPICall()

MakeAPICall takes an API url and returns a HTTPURLResponse

//
//  makeAPICall.swift
//  ServiceApp
//
//  Created by Phillip Jubb on 31/3/21.
//

import Foundation



// MARK: makeAPICall()
//
// Takes URL and credentials and makes API call and returns optional JSON object

func makeAPICall(apiURL: String, requestString: String) -> apiResponse {
    
    var isFetching = true
    var returnValue:  apiResponse = apiResponse()
    var errorValue : Error
    
//    if checkIfOnline(baseurl: apiURL) {
        guard let url = URL(string: apiURL) else {
            print("Exception: malformed URL")
            isFetching = false
            return returnValue
        }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/text", forHTTPHeaderField: "Content-Type")
        let bodydata: Data? = requestString.data(using: .utf8)
        request.httpBody = bodydata
        isFetching = true
        
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data else {
                isFetching = false
                
                return }
       
            if let response  = response as? HTTPURLResponse {
                print("API Status Code: \(response.statusCode)")
                returnValue.response = response
                returnValue.data = data
            }
            
            if let err = error {

            }
            isFetching = false
        }.resume()
        
        while isFetching {
            // WAITING UNTIL API CALL RETURNS
            sleep(2)
        }
//    }
    return returnValue
}