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

일기장 [STEP 3] hoon, karen #140

Open
wants to merge 15 commits into
base: ic_9_karen
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 77 additions & 15 deletions Diary.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

70 changes: 69 additions & 1 deletion Diary/Controller/DiaryDetailViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ final class DiaryDetailViewController: UIViewController, Shareable {

private let diary: Diary
private let isUpdated: Bool
private var latitude: Double?
private var longitude: Double?

private let contentTextView = {
let textView = UITextView()
Expand All @@ -27,16 +29,20 @@ final class DiaryDetailViewController: UIViewController, Shareable {
override func viewDidLoad() {
super.viewDidLoad()
configure()
configureToast()
fetchWeather()
}

override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
saveDiary()
}

init(diary: Diary, isUpdated: Bool = true) {
init(diary: Diary, isUpdated: Bool = true, latitude: Double? = nil, longitude: Double? = nil) {
self.diary = diary
self.isUpdated = isUpdated
self.latitude = latitude
self.longitude = longitude
super.init(nibName: nil, bundle: nil)
}

Expand Down Expand Up @@ -177,3 +183,65 @@ private extension DiaryDetailViewController {
])
}
}

extension DiaryDetailViewController: Toastable {
func configureToast() {
APIKey.delegate = self
}

func showToast(message: String) {
let toastLabel = UILabel(frame: CGRect(
x: self.view.frame.size.width / 2 - 100,
y: self.view.frame.size.height / 2 - 35,
width: 200,
height: 70
))

toastLabel.backgroundColor = UIColor.systemGray
toastLabel.textColor = UIColor.white
toastLabel.font = UIFont.preferredFont(forTextStyle: .body)
toastLabel.textAlignment = .center
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10
toastLabel.clipsToBounds = true
toastLabel.numberOfLines = 0

view.addSubview(toastLabel)
UIView.animate(withDuration: 5.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: { _ in
toastLabel.removeFromSuperview()
})
}
}

private extension DiaryDetailViewController {
func fetchWeather() {
guard let latitude, let longitude else {
return
}

WeatherAPI.Users(
host: HostName.localWeather.address,
path: Path.localWeather.description,
query: Query.localWeather(latitude: latitude, longitude: longitude).parameters
).request { [weak self] result in
switch result {
case .success(let data):
guard let decodedData: Location = try? DecodingManager.decodeData(from: data) else {
return
}

guard let currentWeather = decodedData.weather.first else {
return
}

self?.diary.main = currentWeather.main
self?.diary.icon = currentWeather.icon
case .failure(let error):
print(error.description)
}
}
}
}
33 changes: 31 additions & 2 deletions Diary/Controller/DiaryViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,20 @@
//

import UIKit
import CoreLocation

final class DiaryViewController: UIViewController, Shareable {
typealias Contents = String

private var tableView = UITableView()
private var diaryList = [Diary]()
private var locationManager = CLLocationManager()
private var latitude: Double?
private var longitude: Double?

override func viewDidLoad() {
super.viewDidLoad()
configureLocationManager()
configure()
}

Expand Down Expand Up @@ -79,7 +84,8 @@ extension DiaryViewController: UITableViewDataSource {
cell.configureCell(
title: diary.title,
date: formattedDate,
preview: diary.body
preview: diary.body,
icon: diary.icon
)

return cell
Expand All @@ -101,6 +107,24 @@ private extension DiaryViewController {
}
}

extension DiaryViewController: CLLocationManagerDelegate {
private func configureLocationManager() {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let coordinate = locations.last?.coordinate else {
return
}

latitude = coordinate.latitude
longitude = coordinate.longitude
}
}

private extension DiaryViewController {
func configure() {
configureRootView()
Expand All @@ -118,7 +142,12 @@ private extension DiaryViewController {
func configureNavigation() {
let action = UIAction { [weak self] _ in
let diary = CoreDataManager.shared.create()
let diaryDetailViewController = DiaryDetailViewController(diary: diary, isUpdated: false)
let diaryDetailViewController = DiaryDetailViewController(
diary: diary,
isUpdated: false,
latitude: self?.latitude,
longitude: self?.longitude
)
self?.navigationController?.pushViewController(diaryDetailViewController, animated: true)
}

Expand Down
2 changes: 1 addition & 1 deletion Diary/CoreData/Diary.xcdatamodeld/.xccurrentversion
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
<plist version="1.0">
<dict>
<key>_XCCurrentVersionName</key>
<string>Diary.xcdatamodel</string>
<string>Diary v2.xcdatamodel</string>
</dict>
</plist>
10 changes: 10 additions & 0 deletions Diary/CoreData/Diary.xcdatamodeld/Diary v2.xcdatamodel/contents
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="21754" systemVersion="22G91" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="Diary" representedClassName="Diary" syncable="YES" codeGenerationType="class">
<attribute name="body" optional="YES" attributeType="String"/>
<attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="icon" optional="YES" attributeType="String"/>
<attribute name="main" optional="YES" attributeType="String"/>
<attribute name="title" optional="YES" attributeType="String"/>
</entity>
</model>
90 changes: 90 additions & 0 deletions Diary/CoreData/MappingFile.xcmappingmodel/xcmapping.xml

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions Diary/Network/CacheStore.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//
// CacheStore.swift
// Diary
//
// Created by hoon, karen on 2023/09/15.
//

import UIKit

final class CacheStore {
static let shared = NSCache<NSString, UIImage>()

private init() {}
}
20 changes: 20 additions & 0 deletions Diary/Network/DecodingManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// DecodingManager.swift
// Diary
//
// Created by hoon, karen on 2023/09/14.
//

import Foundation

struct DecodingManager {
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
}
}
17 changes: 17 additions & 0 deletions Diary/Network/Error/DecodingError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// DecodingError.swift
// Diary
//
// Created by hoon, karen on 2023/09/14.
//

enum DecodingError: Error {
case decodingFailure

var description: String {
switch self {
case .decodingFailure:
return "디코딩을 실패하였습니다."
}
}
}
26 changes: 26 additions & 0 deletions Diary/Network/Error/NetworkError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//
// NetworkError.swift
// Diary
//
// Created by hoon, karen on 2023/09/14.
//

enum NetworkError: Error {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

case invalidURL
case failureRequest
case failureResponse
case invalidDataType

var description: String {
switch self {
case .invalidURL:
return "url형식이 잘못되었습니다"
case .failureRequest:
return "데이터 요청에 실패했습니다."
case .failureResponse:
return "응답이 없습니다."
case .invalidDataType:
return "올바르지 않는 데이터 포맷입니다"
}
}
}
83 changes: 83 additions & 0 deletions Diary/Network/Model/Location.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
//
// Location.swift
// Diary
//
// Created by hoon, karen on 2023/09/14.
//

struct Location: Decodable {
let coordinate: Coordinate
let weather: [Weather]
let base: String
let main: Main
let visibility: Int
let wind: Wind
let rain: Rain?
let clouds: Clouds
let date: Int
let sys: Sys
let timezone, id: Int
let name: String
let cod: Int

private enum CodingKeys: String, CodingKey {
case coordinate = "coord"
case weather, base, main, visibility, wind, rain, clouds
case date = "dt"
case sys, timezone, id, name, cod
}
}

struct Coordinate: Decodable {
let longitude: Double
let latitude: Double

private enum CodingKeys: String, CodingKey {
case longitude = "lon"
case latitude = "lat"
}
}

struct Weather: Decodable {
let id: Int
let main, description, icon: String
}

struct Clouds: Decodable {
let all: Int
}

struct Main: Decodable {
let temp, feelsLike, tempMin, tempMax: Double
let pressure, humidity, seaLevel, grndLevel: Int?

enum CodingKeys: String, CodingKey {
case temp
case feelsLike = "feels_like"
case tempMin = "temp_min"
case tempMax = "temp_max"
case pressure, humidity
case seaLevel = "sea_level"
case grndLevel = "grnd_level"
}
}

struct Rain: Decodable {
let the1H: Double

enum CodingKeys: String, CodingKey {
case the1H = "1h"
}
}

struct Sys: Decodable {
let type, id: Int
let country: String
let sunrise, sunset: Int
}

struct Wind: Decodable {
let speed: Double
let deg: Int
let gust: Double
}
Loading