Created
June 7, 2022 17:05
-
-
Save robertmryan/7756a8239d6564385ad341fe6221691f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, a few observations:
post
.if
statements.m_
prefix on your properties. So, for example, the session property is justsession
. If, in a method, you want to remove ambiguity and make it clear you are referencing a property, you would sayself.session
. But, in practice, in well written code, we omit redundantself.
references, as it is generally self-evident and/or not relevant.post
and set those properties to something else.) All the inputs to this method should be method parameters, not properties.!
forced unwrapping operator.URLSession.shared
. If you must instantiate aURLSession
, make sure to invalidate it when you are done.So, factoring all of that, you get something like the above. And you’d call it like: