GTRestKit

class GTRestKit : NSObject, URLSessionTaskDelegate

A lightweight but powerful library for making HTTP requests and consuming RESTful APIs.

  • The collection of the request headers that should be provided before making a HTTP request.

    To add request headers to a request, either access this dictionary directly, or use the add(requestHeader:withValue:) method.

    Declaration

    Swift

    var requestHeaders: [String : String]
  • The HTTP status code of the last made request.

    Declaration

    Swift

    var httpStatusCode: Int?
  • The content type of the response.

    This property gets its value automatically when the server sends a response back. It’s used for the most common content types.

    Declaration

    Swift

    var responseContentType: GTRKResponseContentType?
  • url

    The URL that a request is made to.

    Declaration

    Swift

    var url: URL?
  • The response coming from the server as a URLResponse object.

    It would be also useful to convert it and use it as a HTTPURLResponse object instead:

    if let response = response as? HTTPURLResponse { ... }
    

    Declaration

    Swift

    var response: URLResponse?
  • Undocumented

    Declaration

    Swift

    override init()
  • A convenient method for adding headers to the HTTP request.

    Use this method if you don’t want to add request headers to the requestHeaders property manually. Simply provide the header name and the value as arguments.

    To make it even easier, you can use the GTRKCommonRequestHeaders and GTRKCommonRequestHeaderValues enum values for adding common headers and values to the requestHeaders property.

    Make sure that you always provide request headers prior to making the HTTP request.

    Example:

    let restKit = GTRestKit()
    restKit.add(requestHeader: GTRKCommonRequestHeaders.contentType.rawValue,
                withValue: GTRKCommonRequestHeaderValues.contentTypeApplicationJSON.rawValue)
    
    // ...or by setting the actual values...
    restKit.add(requestHeader: "Content-Type",
                withValue: "application/json")
    

    Declaration

    Swift

    func add(requestHeader header: String, withValue value: String)

    Parameters

    header

    The request header key.

    value

    The request header value.

  • Use this method to perform an HTTP request.

    Before calling this method you would probably want to specify some request headers. To do that, you can use the requestHeaders dictionary directly by setting the headers and their respective values as follows:

    let restKit = GTRestKit()
    restKit.requestHeaders["Content-Type"] = "application/json"
    

    Alternatively, you could use the add(requestHeader:withValue:) convenient method provided:

    let restKit = GTRestKit()
    restKit.add(requestHeader: "Content-Type", withValue: "application/json")
    

    For greater flexibility, you could also use the GTRKCommonRequestHeaders and GTRKCommonRequestHeaderValues enums which both contain some common request headers and their values.

    In case of an error when performing an HTTP request, the results in the completion handler remains nil, while the error object indicates the problem. The error can be a custom one generated by GTRestKit when the request doesn’t return an HTTP status code ranging from 200 to 299, and it can potentialy include a message coming from the server too.

    The results object in the completion handler is an Any object. If you know the actual datatype expected to be returned, then cast to that datatype instantly:

    if let dict = results as? [String: Any] { ... }
    

    If you’re unsure about the server results in case the server returns multiple result types (JSON, plain text, etc), then you could use the responseContentType property in case the results type has been recongized automatically. Here’s an example:

    if let contentType = restKit.responseContentType {
        if contentType == GTRKResponseContentType.textPlain || contentType == GTRKResponseContentType.textHTML {
            print(results as! String)
        } else if contentType == GTRKResponseContentType.applicationJSON {
            print(results as! [String:  Any])
        }
    }
    

    Lastly, you cannot use this method to upload files. To do so, see the uploadFiles(toURL:usingHTTPMethod:urlParams:bodyParams:filesInfo:completionHandler:) method.

    Declaration

    Swift

    func makeRequest(toURL url: String, usingHTTPMethod httpMethod: GTRKHTTPMethod, urlParams: [String: String]?, bodyParams: [String: Any]?, completionHandler: @escaping (_ results: Any?, _ error: Error?) -> Void)

    Parameters

    url

    The request URL (endpoint) as a string value.

    httpMethod

    The HTTP method (GET, POST, etc) to use in the request. See the GTRKHTTPMethod for more information.

    urlParams

    Any query parameters you want to pass along with the request through the URL.

    bodyParams

    Any body parameters you want to send along with the request. These parameters are sent as JSON object.

    completionHandler

    A completion handler that includes the results from the server in case everything ran smoothly and no error exists, and an error object in case something bad happens.

  • Use this method to perform an HTTP request and upload one or more files to the server.

    Your request can include URL parameters or body parameters as well that will be sent along with the files.

    To include a file in your request, you must initialize and use a GTRKFileInfo object:

    var fileInfo = GTRKFileInfo()
    if let path = Bundle.main.path(forResource: "car", ofType: "png") {
        fileInfo.fileContent = try? Data(contentsOf: URL(fileURLWithPath: path))
        fileInfo.mimetype = GTRKMimeTypes.imagePNG.rawValue
        fileInfo.filename = "car.png"
    }
    

    If any of the properties shown in the snippet above is nil, the file won’t be uploaded.

    To include that file to the request, simply provide it as an argument to this method, but always as an array item, even if you’re uploading just one file:

    restKit.uploadFiles(toURL: SOME_URL, usingHTTPMethod: .POST, urlParams: nil, bodyParams: nil, filesInfo: [fileInfo]) { (results, error) in
        ...
    }
    

    All the above apply when uploading multiple files too. Regarding the mimetype property, you can either set it directly:

    fileInfo.mimetype = "image/png"
    

    or you can use the GTRKMimeTypes enum and pick a value from there:

    fileInfo.mimetype = GTRKMimeTypes.imagePNG.rawValue
    

    For more information, see the GTRKMimeTypes enum.

    Also, for more general details about using this method, see the documentation of the makeRequest(toURL:usingHTTPMethod:urlParams:bodyParams:completionHandler:) method which is quite similar.

    Declaration

    Swift

    func uploadFiles(toURL url: String, usingHTTPMethod httpMethod: GTRKHTTPMethod, urlParams: [String: String]?, bodyParams: [String: Any]?, filesInfo: [GTRKFileInfo], completionHandler: @escaping (_ results: Any?, _ error: Error?) -> Void)

    Parameters

    url

    The request URL (endpoint) as a string value.

    httpMethod

    The HTTP method (GET, POST, etc) to use in the request. See the GTRKHTTPMethod for more information.

    urlParams

    Any query parameters you want to pass along with the request through the URL.

    bodyParams

    Any body parameters you want to send along with the request. These parameters are sent as JSON object.

    filesInfo

    A collection of GTRKFileInfo objects regarding the file or files that should be uploaded to the server.

    completionHandler

    A completion handler that includes the results from the server in case everything ran smoothly and no error exists, and an error object in case something bad happens.