Skip to content

Instantly share code, notes, and snippets.

@tarang9211
Created July 3, 2020 09:36
Show Gist options
  • Select an option

  • Save tarang9211/38bc13adf76305cf9d2b4ab83e30d163 to your computer and use it in GitHub Desktop.

Select an option

Save tarang9211/38bc13adf76305cf9d2b4ab83e30d163 to your computer and use it in GitHub Desktop.

Revisions

  1. tarang9211 created this gist Jul 3, 2020.
    40 changes: 40 additions & 0 deletions swift-composing-types.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    typealias DCRequestType = (URLRequest, Error)

    //basically makePostRequest should be a function that returns a URLRequest. Straightforward.
    // I want the return type to be either a URlRequest or an Error. <URLRequest, Error> something of this kind.
    // You see what I'm doing right?

    fileprivate func makePostRequest(apiUrl: String, params: [String: String]) -> <URLRequest, Error> {
    // build url
    let urlString = "\(dcoderURL)\(apiUrl)"
    guard let serviceUrl = URL(string: urlString) else { return nil }

    // build url request
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")

    //set http body for url request with incoming params
    guard let httpBody = try? JSONSerialization.data(withJSONObject: params, options: []) else {
    return nil
    }
    request.httpBody = httpBody
    return request
    }
    }

    //The code about would make lines 29-36 obsolete with just one go. The error can be consumed here to actually throw it back to the UI

    // func sendRegistrationCode(userEmail:String, username:String, userPassword:String, userUsername:String, completion: @escaping (SendCodeModel?, Error?) -> ()) {

    // let urlString = "\(dcoderURL)\(sendRegistrationCodeURL)"
    // let params = ["user_email":userEmail,"user_name":username,"user_password":userPassword,"user_username":userUsername]
    // guard let serviceUrl = URL(string: urlString) else { return }
    // var request = URLRequest(url: serviceUrl)
    // request.httpMethod = "POST"
    // request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    // guard let httpBody = try? JSONSerialization.data(withJSONObject: params, options: []) else {
    // return
    // }
    // request.httpBody = httpBody
    // }