Ricki Moore Ricki Moore - 1 year ago 38
Swift Question

Make Swift Class to make Http Requests

I made this class below to help make http requests from anywhere in my application, however when i call the class it does not make the request as expected. I see i can print from the function so i know it is making it that far at least. What else do i need to make this request?? the api parameter is being passed correctly as well.

in viewController:

let url = "post/test"
MakeHttpRequest.sharedInstance.postRequest(api: url)


in class:

import Foundation

final class MakeHttpRequest {
static let sharedInstance = MakeHttpRequest()
var api_token = "token_here"
var url_base = "https://test.frb.io/"
func postRequest (api : String) {
let parameters = ["email": "[email protected]"]
guard let destination = URL(string: url_base + api) else { return }
var request = URLRequest(url: destination)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// request.setValue("clientIDhere", forHTTPHeaderField: "Authorization")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if (json["response"]) != nil {

}
} catch {
print(error)
}
}
}.resume()
print(url_base + api)
}
private init() {
}
}

Answer Source

So two things to check. Sometimes swift function chaining doesn't work properly. So try splitting the session.dataTask and resume into two statements. And second try adding error handling to the response. You may be getting an error without knowing it. See code sample below.

import Foundation

final class MakeHttpRequest {
    static let sharedInstance = MakeHttpRequest()
    var api_token = "token_here"
    var url_base = "https://test.frb.io/"
    func postRequest (api: String, parameters: [String: Any]? = nil) {
        guard let destination = URL(string: url_base + api) else { return }
        var request = URLRequest(url: destination)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        //            request.setValue("clientIDhere", forHTTPHeaderField: "Authorization")
        if let parameters = parameters {
            guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return
            }
            request.httpBody = httpBody
        }
        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, response, error) in
            if let data = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    if (json["response"]) != nil {
                        print("1234")
                    } else {
                        print("ABCD")
                    }
                } catch {
                    print(error)
                }
            } else {
                print(error ?? "")
            }
        }
        task.resume()
        print(url_base + api)
    }

    private init() {
    }
}

let url = "post/test"
MakeHttpRequest.sharedInstance.postRequest(api: url)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download