Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created June 7, 2022 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/7756a8239d6564385ad341fe6221691f to your computer and use it in GitHub Desktop.
Save robertmryan/7756a8239d6564385ad341fe6221691f to your computer and use it in GitHub Desktop.
class NetworkManager {
let session: URLSession = {
let session = URLSession(configuration: .default)
return session
}()
deinit {
session.finishTasksAndInvalidate()
}
func post(
url: URL,
parameters: String,
headers: [String: String]? = nil,
completion: @escaping (Data?, URLResponse?, Error?) -> Void
) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = parameters.data(using: .utf8)
request.allHTTPHeaderFields = headers
let task = session.dataTask(with: request, completionHandler: completion)
task.resume()
}
}
@robertmryan
Copy link
Author

robertmryan commented Jun 7, 2022

So, a few observations:

  1. Simplify the name to just post.
  2. Use camelCase for method names.
  3. Do not use semicolons.
  4. Do not use parentheses in if statements.
  5. Do not use the m_ prefix on your properties. So, for example, the session property is just session. If, in a method, you want to remove ambiguity and make it clear you are referencing a property, you would say self.session. But, in practice, in well written code, we omit redundant self. references, as it is generally self-evident and/or not relevant.
  6. Don’t rely on properties where you don’t need to, anyway. It introduces race risks. (E.g., imagine that some other thread wanted to do its own call to post and set those properties to something else.) All the inputs to this method should be method parameters, not properties.
  7. Do not use optionals where you don’t need to.
  8. Avoid the ! forced unwrapping operator.
  9. Where possible, use URLSession.shared. If you must instantiate a URLSession, make sure to invalidate it when you are done.
  10. If you are going to edit the session’s headers, this is not the right place to do it. Either update the session headers before you start issuing requests, or just update the headers for the particular request.

So, factoring all of that, you get something like the above. And you’d call it like:

post(url: url, parameters: ["foo": "bar"]) { data, response, error in
     // handle the response here
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment