JeongAh Hong
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    @lina0322 엘림 안녕하세요! Step2 PR을 보냅니다! - 지난번 엘림의 피드백을 통해 더욱 깊이 생각해보는 시간을 가질 수 있었습니다 🙏 최대한 피드백들을 반영해보았는데 일부 내용들은 이후 단계에서 고민하고 적용하는 것이 나을 것 같아 보류해두었습니다. - 일단 이번 스텝을 진행하면서 저희가 가장 고민되었던 부분은 여러가지 모델 타입을 어떻게 하나의 메서드에서 파싱할 것인가 였습니다. 사실 파싱 메서드를 제네릭 타입으로 만들어서 문제가 없다고 생각했는데 Result타입의 결과를 처리하는 부분 때문에 많은 어려움을 겪었던 것 같습니다. 저희가 실제 커밋한 코드 외에도 시도해보았던(그러나 장렬히 실패한😭 ) 코드도 두 가지 버전을 첨부합니다. 조언 부탁드려요! 🤩 # 궁금점/고민 ### 1. [startUpdatingLocation()](https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation) 저희가 이해하기로는 `startUpdatingLocation()` 함수를 한번만 호출하면 알아서 위치가 바뀔 때마다 업데이트해주는 것 같습니다. 따라서 LocationManager가 생성될 때 한번만 실행하도록 구현했는데 맞게 이해한 것인지 궁금합니다. ### 2. 메서드명이 동일 LocationManager와 ViewController가 `getAddress(of:)`라는 동일한 메서드명을 가진 함수를 갖고 있습니다. 각기 다른 타입의 인스턴스 메서드라 상관없을 것 같으면서도 살짝 찜찜한데 이 부분에 대해 어떻게 생각하시는지 궁금합니다 🤩 ### 3. dataTask 중복 요청에 대한 처리 로직 변경 - 요청을 중복적으로 처리하는 것을 방어하기 위한 로직을 개선했습니다. 근데 해당 커밋의 타입이 fix인지 refactor인지 feat인지 고민이 되었습니다. - 기존에는 서로 다른 요청이라도 연속적으로 들어오면 앞선 요청을 취소해버리는 문제가 있었고 경우에 따라 버그라고 인식될 수 잇을 것 같아 fix라고 지정했습니다. - 하지만 당장은 버그가 있지 않았기 때문에 아무것도 해결되지 않은 것처럼 보이는데 이 부분에 대한 엘림의 생각이 궁금합니다 🤔 ### 4. CurrentWeather와 FiveDayWeather의 network요청을 하나의 함수에서 처리 (파싱도 마찬가지) 네트워크 요청으로 날씨 데이터를 받아올 때 CurrentWeather 타입과 FiveDayWeather 타입을 모두 하나의 함수에서 처리하고 싶었습니다. 따라서 `getWeatherData(of:route:)`로 현재날씨도 받아올 수 있고 5일치 날씨도 받아올 수 있도록 구현해보았습니다. - 하지만 파싱을 담당하는 `extract(data:period:)`도 현재 날씨와 5일치 날씨를 모두 파싱할 수 있도록 하려다보니 switch문 안에 switch문이 들어가게 되었습니다. 이 부분을 하나의 switch문만 사용하도록 시도해봤는데 실패했습니다 😫 ```swift private func extract(data: Data, period: WeatherForecastRoute) { switch period { case .current: let parsedData = data.parse(to: CurrentWeather.self) switch parsedData { case .success(let currentWeatherData): self.currentWeather = currentWeatherData case .failure(let parsingError): assertionFailure(parsingError.localizedDescription) } case .fiveDay: let parsedData = data.parse(to: FiveDayWeather.self) switch parsedData { case .success(let fiveDayWeatherData): self.fiveDayWeather = fiveDayWeatherData case .failure(let parsingError): assertionFailure(parsingError.localizedDescription) } } } ``` #### 4-1. `extract(data:period)`의 switch문을 분리하려는 시도 - 예를 들어 parsedData의 결과가 .success()인지 .failure()인지에 따라 처리하는 switch문을 `filter(parsedData:)`라는 함수로 따로 빼보았습니다. - CurrentWeather와 FiveDayWeather를 WeatherModel 타입으로 추상화해서 `filter(parsedData:)`가 이 추상화된 타입을 매개변수로 전달받도록 했습니다. - `extract(data:period:)`에게 CurrentWeather 타입의 데이터 파싱을 요청해보았더니 다음 이미지와 같이 Result<CurrentWeather, ParsingError>타입을 Result<WeatherModel, ParsingError> 타입에 담을 수 없다는 에러가 발생했습니다. 🤯 ![image](https://user-images.githubusercontent.com/52592748/136514211-9fed3443-380c-423f-beca-3fd68926ec56.png) 저희가 시도해본 코드를 첨부합니다 ```swift protocol WeatherModel {} extension CurrentWeather: WeatherModel {} extension FiveDayWeather: WeatherModel {} private func extract(data: Data, period: WeatherForecastRoute) { switch period { case .current: let parsedData = data.parse(to: CurrentWeather.self) filter(parsedData: parsedData) case .fiveDay: let parsedData = data.parse(to: FiveDayWeather.self) switch parsedData { case .success(let fiveDayWeatherData): self.fiveDayWeather = fiveDayWeatherData case .failure(let parsingError): assertionFailure(parsingError.localizedDescription) } } } private func filter(parsedData: Result<WeatherModel, ParsingError>) { switch parsedData { case .success(let data): if let weatherData = data as? CurrentWeather { currentWeather = weatherData } else if let weatherData = data as? FiveDayWeather { fiveDayWeather = weatherData } case .failure(let parsingError): assertionFailure(parsingError.localizedDescription) } } ``` #### 4-2. 파싱 로직을 NetworkModule에서 진행하는 시도 - NetworkManager와 NetworkModule을 제니릭 타입으로 변경하고 NetworkModule에서 바로 파싱을 진행하도록 수정했습니다. <details> <summary> <b> NetworkManager와 NetworkModule 코드 </b> </summary> <div markdown="1"> ```swift struct NetworkManager { private var networkable: Networkable init(networkable: Networkable = NetworkModule()) { self.networkable = networkable } mutating func request<T: Decodable>(type: T, with route: Route, queryItems: [URLQueryItem]?, header: [String: String]? = nil, bodyParameters: [String: Any]? = nil, httpMethod: HTTPMethod, requestType: URLRequestTask, completionHandler: @escaping (Result<T, Error>) -> Void) { guard let urlRequest = requestType.buildRequest(route: route, queryItems: queryItems, header: header, bodyParameters: bodyParameters, httpMethod: httpMethod) else { completionHandler(.failure(NetworkError.invalidURL)) return } networkable.runDataTask(type: type, request: urlRequest, completionHandler: completionHandler) } } ``` ```swift struct NetworkModule: Networkable { private let rangeOfSuccessState = 200...299 private var dataTask: [URLSessionDataTask] = [] mutating func runDataTask<T: Decodable>(type: T, request: URLRequest, completionHandler: @escaping (Result<T, Error>) -> Void) { dataTask.enumerated().forEach { (index, task) in if let originalRequest = task.originalRequest, originalRequest == request { task.cancel() dataTask.remove(at: index) } } let task = URLSession.shared.dataTask(with: request) { [self] (data, response, error) in if let error = error { DispatchQueue.main.async { completionHandler(.failure(error)) } return } guard let response = response as? HTTPURLResponse, rangeOfSuccessState.contains(response.statusCode) else { DispatchQueue.main.async { completionHandler(.failure(NetworkError.badResponse)) } return } guard let data = data else { DispatchQueue.main.async { completionHandler(.failure(NetworkError.invalidData)) } return } DispatchQueue.main.async { let result = data.parse(to: T.self) switch result { case .success(let parsed): completionHandler(.success(parsed)) case .failure(let error): completionHandler(.failure(error)) } } task.resume() dataTask.append(task) } } ``` ```swift protocol Networkable { mutating func runDataTask<T: Decodable>(type: T, request: URLRequest, completionHandler: @escaping (Result<T,Error>) -> Void) } ``` </div> </details> <br> - 이번에도 CurrentWeather와 FiveDayWeather타입을 WeatherModule 타입으로 추상화해주었습니다. - 그리고 날씨를 받아오는 부분을 다음과 같이 하나의 메서드에서 처리해주었습니다. ```swift protocol WeatherModel: Decodable {} extension CurrentWeather: WeatherModel {} extension FiveDayWeather: WeatherModel {} private func getWeatherData<WeatherModel: Decodable>(type: WeatherModel, of location: CLLocation, route: WeatherForecastRoute) { let queryItems = WeatherForecastRoute.createParameters(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) networkManager.request(type: type, with: route, queryItems: queryItems, httpMethod: .get, requestType: .requestWithQueryItems) { (result: Result<WeatherModel, Error>) in switch result { case .success(let data): if let weatherData = data as? CurrentWeather { self.currentWeather = weatherData } else if let weatherData = data as? FiveDayWeather { self.fiveDayWeather = weatherData } case .failure(let error): assertionFailure(error.localizedDescription) } } } ``` - 여기까지는 문제가 없었는데 뷰컨의 `initData()`에서 `getWeatherData(type:of:route:)`를 호출하니 다음과 같은 에러가 발생했는데 원인을 파악하지 못했습니다 ㅜ - (뭔가를 어떻게 바꿨더니 WeatherModel이 프로토콜 타입이라 Decodable을 따를 수 없다는 에러도 떴던 것 같습니다 😭) ![image](https://user-images.githubusercontent.com/52592748/136516097-78e30c53-0ea4-40cb-a7c5-05b2cc3698e5.png) ```swift class ViewController: UIViewController { private var networkManager = NetworkManager() private let locationManager = LocationManager() private var currentWeather: CurrentWeather? private var fiveDayWeather: FiveDayWeather? override func viewDidLoad() { super.viewDidLoad() initData() } private func initData() { guard let location = locationManager.getGeographicCoordinates() else { return } getWeatherData(type: CurrentWeather, of: location, route: .current) getWeatherData(type: FiveDayWeather, of: location, route: .fiveDay) } } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully