Skip to content

Commit

Permalink
feat: NetworkNamager
Browse files Browse the repository at this point in the history
  • Loading branch information
hemg2 committed Sep 13, 2023
1 parent f4130a9 commit 036cfb6
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Diary/Model/DecodingManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,14 @@ final class DecodingManager {

return decodedData
}

static func decodeData<T: Decodable>(from data: Data) throws -> T {
let decoder = JSONDecoder()

guard let decodedData = try? decoder.decode(T.self, from: data) else {
throw DecodingError.decodingFailure
}

return decodedData
}
}
56 changes: 56 additions & 0 deletions Diary/Network/NetworkManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//
// NetworkManager.swift
// Diary
//
// Created by Max, Hemg on 2023/09/13.
//

import CoreLocation

final class NetworkManager {
private var dataTask: URLSessionDataTask?

func fetchData(url: String, completionHandler: @escaping(Result<Data, APIError>) -> Void) {
guard let url = URL(string: url) else {
completionHandler(.failure(.invalidURL))
return
}

dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
if error != nil {
completionHandler(.failure(.requestFail))
}

guard let httpResponse = response as? HTTPURLResponse, (200...299) ~= httpResponse.statusCode else {
completionHandler(.failure(.invalidData))
return
}

guard let data else {
completionHandler(.failure(.invalidData))
return
}

completionHandler(.success(data))
}
self.dataTask?.resume()
}

func fetchLocation(location: CLLocation, _ completionHandler: @escaping(Result<WeatherResult, APIError>) -> Void) {
let urlStr = "https://api.openweathermap.org/data/2.5/weather?lat=\(location.coordinate.latitude)&lon=\(location.coordinate.longitude)&appid=aaa5700cbd82d1a09e738731002f97be"

fetchData(url: urlStr) { result in
switch result {
case .success(let data):
do {
let decodingData: WeatherResult = try DecodingManager.decodeData(from: data)
completionHandler(.success(decodingData))
} catch {
completionHandler(.failure(APIError.decodingFail))
}
case .failure(let error):
completionHandler(.failure(error))
}
}
}
}

0 comments on commit 036cfb6

Please sign in to comment.