Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

๐Ÿ•“ 4์ฃผ์ฐจ ์„ธ๋ฏธ๋‚˜ #13

Merged
merged 4 commits into from
Aug 14, 2023
Merged

Conversation

ena-isme
Copy link
Contributor

@ena-isme ena-isme commented Aug 14, 2023

4์ฃผ์ฐจ

4์ฃผ์ฐจ ์„ธ๋ฏธ๋‚˜์—์„œ๋Š” Alamofire ๋ฅผ ํ†ตํ•ด ๋‚ ์”จAPI ๋ฅผ ์—ฐ๊ฒฐํ•˜์˜€์Šต๋‹ˆ๋‹ค. TableView Cell ์— ๋‚ ์”จ API๋ฅผ ์—ฐ๊ฒฐํ•˜์—ฌ ๋„คํŠธ์›Œํฌ ํ†ต์‹ ์„ ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค.


์ฃผ์š”์ฝ”๋“œ


๋„คํŠธ์›Œํฌ ํ†ต์‹ ์—์„œ ๊ฐ€์žฅ ์ฃผ์š”ํ•œ ์ฝ”๋“œ๋Š” WeatherService ์ž…๋‹ˆ๋‹ค :)


final class WeatherService {
    
    let baseURL = "https://api.openweathermap.org/data/2.5/weather?"
    static let shared = WeatherService()

    private init() {}

    func getWeather(city : String, completion : @escaping (NetworkResult<Any>) -> Void) {
        let url = "https://api.openweathermap.org/data/2.5/weather"
        let header: HTTPHeaders = ["Content-Type" : "application/json"]
        let body: Parameters = [
            "q": city,
            "appid": "9c7fa18b50b00954d1159672fb66a924",
        ]

        let dataRequest = AF.request(url, method: .get,
                                     parameters : body,
                                     headers: header)

        dataRequest.responseData { response in
            switch response.result {
            case .success:
                guard let statusCode = response.response?.statusCode else { return }
                guard let value = response.value else { return }
                let networkResult = self.judgeStatus(by: statusCode, value)
                completion(networkResult)
            case .failure:
                completion(.networkErr)
            }
        }
    }
    private func judgeStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
        switch statusCode {
        case 200: return isValidData(data: data)
        case 400...409: return isValidData(data: data)
        case 500: return .serverErr
        default: return .networkErr
        }
    }

    private func isValidData(data: Data) -> NetworkResult<Any> {
        let decoder = JSONDecoder()

        guard let decodedData = try? decoder.decode(Weathers.self, from: data) else { return .pathErr }

        return .success(decodedData as Any)
    }
}

์‹ค์Šต๊ฒฐ๊ณผ


Simulator.Screen.Recording.-.iPhone.14.Pro.-.2023-08-15.at.04.41.08.mp4

@ena-isme ena-isme merged commit d7a4534 into main Aug 14, 2023
@ena-isme ena-isme self-assigned this Aug 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant