Skip to content

Instantly share code, notes, and snippets.

@SlappyAUS
Last active October 9, 2020 23:50
Show Gist options
  • Save SlappyAUS/20fb4b26a4ab3fee2a5addf63c6f3346 to your computer and use it in GitHub Desktop.
Save SlappyAUS/20fb4b26a4ab3fee2a5addf63c6f3346 to your computer and use it in GitHub Desktop.
HTTP Request - Making Request #network #http
// Apply Delegate to the UIViewController
protocol CoinManagerDelegate {
func didUpdateData(_ sender: CoinManager, parsedData: BitcoinData)
func didFailWithError(_ sender: CoinManager, error: Error)
}
// Insert these calls into the component making the call (Manager class)
func performRequest(with urlString: String) {
let url = URL(string: urlString)
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "GET"
// // Set HTTP Request Header
// request.setValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check if Error took place
if let error = error {
self.delegate?.didFailWithError(self, error: error)
return
}
if let safeData = data {
if let parsedData = self.parseJSON(safeData) {
self.delegate?.didUpdateData(self, parsedData: parsedData)
}
}
// // Read HTTP Response Status code
// if let response = response as? HTTPURLResponse {
// print("Response HTTP Status code: \(response.statusCode)")
// }
//
// // Convert HTTP Response Data to a simple String
// if let data = data, let dataString = String(data: data, encoding: .utf8) {
// print("Response data string:\n \(dataString)")
// }
}
task.resume()
}
func parseJSON(_ requestData: Data)-> BitcoinData? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(BitcoinData.self, from: requestData)
// Alternatively map decodedData to a more succient model
return decodedData
} catch {
self.delegate?.didFailWithError(self, error: error)
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment