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 1] garden #12

Open
wants to merge 7 commits into
base: rft_1_garden
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
8 changes: 8 additions & 0 deletions WeatherForecast/WeatherForecast.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
C7743D992B21C38200DF0D09 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = C7743D972B21C38200DF0D09 /* LaunchScreen.storyboard */; };
C7743DA12B21C3B400DF0D09 /* WeatherTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7743DA02B21C3B400DF0D09 /* WeatherTableViewCell.swift */; };
C7743DA32B21CA8600DF0D09 /* WeatherDetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7743DA22B21CA8500DF0D09 /* WeatherDetailViewController.swift */; };
FFC9B6D92B6FB0DD00BBFBE1 /* NetworkService.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFC9B6D82B6FB0DD00BBFBE1 /* NetworkService.swift */; };
FFC9B6DB2B6FB11F00BBFBE1 /* Protocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFC9B6DA2B6FB11F00BBFBE1 /* Protocol.swift */; };
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
Expand All @@ -30,6 +32,8 @@
C7743D9A2B21C38200DF0D09 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C7743DA02B21C3B400DF0D09 /* WeatherTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherTableViewCell.swift; sourceTree = "<group>"; };
C7743DA22B21CA8500DF0D09 /* WeatherDetailViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherDetailViewController.swift; sourceTree = "<group>"; };
FFC9B6D82B6FB0DD00BBFBE1 /* NetworkService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkService.swift; sourceTree = "<group>"; };
FFC9B6DA2B6FB11F00BBFBE1 /* Protocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Protocol.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -65,7 +69,9 @@
C7743D8C2B21C38100DF0D09 /* AppDelegate.swift */,
C7743D8E2B21C38100DF0D09 /* SceneDelegate.swift */,
C7743DA02B21C3B400DF0D09 /* WeatherTableViewCell.swift */,
FFC9B6DA2B6FB11F00BBFBE1 /* Protocol.swift */,
C7743D902B21C38100DF0D09 /* ViewController.swift */,
FFC9B6D82B6FB0DD00BBFBE1 /* NetworkService.swift */,
C741F66F2B58F00500A4DDC0 /* Weather.swift */,
C7743DA22B21CA8500DF0D09 /* WeatherDetailViewController.swift */,
C7743D922B21C38100DF0D09 /* Main.storyboard */,
Expand Down Expand Up @@ -150,9 +156,11 @@
C7743DA12B21C3B400DF0D09 /* WeatherTableViewCell.swift in Sources */,
C7743D912B21C38100DF0D09 /* ViewController.swift in Sources */,
C7743D8D2B21C38100DF0D09 /* AppDelegate.swift in Sources */,
FFC9B6DB2B6FB11F00BBFBE1 /* Protocol.swift in Sources */,
C7743DA32B21CA8600DF0D09 /* WeatherDetailViewController.swift in Sources */,
C741F6702B58F00500A4DDC0 /* Weather.swift in Sources */,
C7743D8F2B21C38100DF0D09 /* SceneDelegate.swift in Sources */,
FFC9B6D92B6FB0DD00BBFBE1 /* NetworkService.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
40 changes: 40 additions & 0 deletions WeatherForecast/WeatherForecast/NetworkService.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//
// NetworkService.swift
// WeatherForecast
//
// Created by 김정원 on 2/4/24.
//
import Foundation
import UIKit
gadisom marked this conversation as resolved.
Show resolved Hide resolved
final class NetworkService {
static let shared = NetworkService()
private init() {}

func fetchWeatherJSON(weatherInfo :WeatherJSON?) -> WeatherJSON?{
gadisom marked this conversation as resolved.
Show resolved Hide resolved
gadisom marked this conversation as resolved.
Show resolved Hide resolved
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
guard let data = NSDataAsset(name: "weather")?.data else {
return nil
}
let info: WeatherJSON
do {
info = try jsonDecoder.decode(WeatherJSON.self, from: data)
} catch {
print(error.localizedDescription)
return nil
}
return info
}
func fetchWeatherIconImage(iconName: String) async -> UIImage? {
let urlString = "https://openweathermap.org/img/wn/\(iconName)@2x.png"
guard let url = URL(string: urlString) else { return nil }

do {
let (data, _) = try await URLSession.shared.data(from: url)
return UIImage(data: data)
} catch {
print("Error fetching weather icon: \(error)")
return nil
}
}
}
14 changes: 14 additions & 0 deletions WeatherForecast/WeatherForecast/Protocol.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//
// Protocol.swift
// WeatherForecast
//
// Created by 김정원 on 2/4/24.
//

import Foundation

protocol WeatherForeCastDelegate: AnyObject {
func fetchWeatherInfo() -> WeatherForecastInfo
func fetchCityInfo() -> City
func fetchTempUnit() -> TempUnit
}
85 changes: 20 additions & 65 deletions WeatherForecast/WeatherForecast/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,13 @@

import UIKit

class ViewController: UIViewController {
final class ViewController: UIViewController {
havilog marked this conversation as resolved.
Show resolved Hide resolved
var tableView: UITableView!
let refreshControl: UIRefreshControl = UIRefreshControl()
var weatherJSON: WeatherJSON?
var icons: [UIImage]?
let imageChache: NSCache<NSString, UIImage> = NSCache()
let dateFormatter: DateFormatter = {
let formatter: DateFormatter = DateFormatter()
formatter.locale = .init(identifier: "ko_KR")
formatter.dateFormat = "yyyy-MM-dd(EEEEE) a HH:mm"
return formatter
}()

var tempUnit: TempUnit = .metric

var selectIndex : IndexPath!
gadisom marked this conversation as resolved.
Show resolved Hide resolved
override func viewDidLoad() {
super.viewDidLoad()
initialSetUp()
Expand All @@ -41,7 +33,7 @@ extension ViewController {
}

@objc private func refresh() {
fetchWeatherJSON()
loadJSON()
tableView.reloadData()
refreshControl.endRefreshing()
}
Expand Down Expand Up @@ -78,24 +70,8 @@ extension ViewController {
}

extension ViewController {
private func fetchWeatherJSON() {

let jsonDecoder: JSONDecoder = .init()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase

guard let data = NSDataAsset(name: "weather")?.data else {
return
}

let info: WeatherJSON
do {
info = try jsonDecoder.decode(WeatherJSON.self, from: data)
} catch {
print(error.localizedDescription)
return
}

weatherJSON = info
private func loadJSON() {
weatherJSON = NetworkService.shared.fetchWeatherJSON(weatherInfo: weatherJSON)
navigationItem.title = weatherJSON?.city.name
}
}
Expand All @@ -112,55 +88,34 @@ extension ViewController: UITableViewDataSource {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "WeatherCell", for: indexPath)

guard let cell: WeatherTableViewCell = cell as? WeatherTableViewCell,
let weatherForecastInfo = weatherJSON?.weatherForecast[indexPath.row] else {
return cell
}

cell.weatherLabel.text = weatherForecastInfo.weather.main
cell.descriptionLabel.text = weatherForecastInfo.weather.description
cell.temperatureLabel.text = "\(weatherForecastInfo.main.temp)\(tempUnit.expression)"

let date: Date = Date(timeIntervalSince1970: weatherForecastInfo.dt)
cell.dateLabel.text = dateFormatter.string(from: date)

let iconName: String = weatherForecastInfo.weather.icon
let urlString: String = "https://openweathermap.org/img/wn/\(iconName)@2x.png"

if let image = imageChache.object(forKey: urlString as NSString) {
cell.weatherIcon.image = image
return cell
}

Task {
guard let url: URL = URL(string: urlString),
let (data, _) = try? await URLSession.shared.data(from: url),
let image: UIImage = UIImage(data: data) else {
return
}

imageChache.setObject(image, forKey: urlString as NSString)

if indexPath == tableView.indexPath(for: cell) {
cell.weatherIcon.image = image
}
}

cell.configure(info: weatherForecastInfo, tempUnit: tempUnit)
return cell
}
}

extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)

selectIndex = indexPath
let detailViewController: WeatherDetailViewController = WeatherDetailViewController()
detailViewController.weatherForecastInfo = weatherJSON?.weatherForecast[indexPath.row]
detailViewController.cityInfo = weatherJSON?.city
detailViewController.tempUnit = tempUnit
detailViewController.delegate = self
navigationController?.show(detailViewController, sender: self)
}
}


extension ViewController: WeatherForeCastDelegate{

func fetchWeatherInfo() -> WeatherForecastInfo {
return (NetworkService.shared.fetchWeatherJSON(weatherInfo: weatherJSON)?.weatherForecast[selectIndex.row])! // 선택한 셀의 정보 넘기기
}
func fetchCityInfo() -> City {
return (NetworkService.shared.fetchWeatherJSON(weatherInfo: weatherJSON)?.city)!
}
func fetchTempUnit() -> TempUnit {
return tempUnit
}
}
1 change: 0 additions & 1 deletion WeatherForecast/WeatherForecast/Weather.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,3 @@ enum TempUnit: String {
}
}
}

91 changes: 48 additions & 43 deletions WeatherForecast/WeatherForecast/WeatherDetailViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,22 @@

import UIKit

class WeatherDetailViewController: UIViewController {

var weatherForecastInfo: WeatherForecastInfo?
var cityInfo: City?
var tempUnit: TempUnit = .metric
final class WeatherDetailViewController: UIViewController {

let iconImageView: UIImageView = UIImageView()
let weatherGroupLabel: UILabel = UILabel()
let weatherDescriptionLabel: UILabel = UILabel()
let temperatureLabel: UILabel = UILabel()
let feelsLikeLabel: UILabel = UILabel()
let maximumTemperatureLable: UILabel = UILabel()
let minimumTemperatureLable: UILabel = UILabel()
let popLabel: UILabel = UILabel()
let humidityLabel: UILabel = UILabel()
let sunriseTimeLabel: UILabel = UILabel()
let sunsetTimeLabel: UILabel = UILabel()
let spacingView: UIView = UIView()
Copy link

Choose a reason for hiding this comment

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

  1. 접근 제어자가 붙으면 좋을 거 같아요.
  2. 아래와 같이 쓰면 조금 더 코드 량이 줄어들거 같네용
Suggested change
let iconImageView: UIImageView = UIImageView()
let weatherGroupLabel: UILabel = UILabel()
let weatherDescriptionLabel: UILabel = UILabel()
let temperatureLabel: UILabel = UILabel()
let feelsLikeLabel: UILabel = UILabel()
let maximumTemperatureLable: UILabel = UILabel()
let minimumTemperatureLable: UILabel = UILabel()
let popLabel: UILabel = UILabel()
let humidityLabel: UILabel = UILabel()
let sunriseTimeLabel: UILabel = UILabel()
let sunsetTimeLabel: UILabel = UILabel()
let spacingView: UIView = UIView()
let iconImageView: UIImageView = .init()

weak var delegate: WeatherForeCastDelegate?
var weahterJSON: WeatherJSON!
let dateFormatter: DateFormatter = {
let formatter: DateFormatter = DateFormatter()
formatter.locale = .init(identifier: "ko_KR")
Expand All @@ -22,28 +32,11 @@ class WeatherDetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
initialSetUp()
setupData()
}

private func initialSetUp() {
view.backgroundColor = .white

guard let listInfo = weatherForecastInfo else { return }

let date: Date = Date(timeIntervalSince1970: listInfo.dt)
navigationItem.title = dateFormatter.string(from: date)

let iconImageView: UIImageView = UIImageView()
let weatherGroupLabel: UILabel = UILabel()
let weatherDescriptionLabel: UILabel = UILabel()
let temperatureLabel: UILabel = UILabel()
let feelsLikeLabel: UILabel = UILabel()
let maximumTemperatureLable: UILabel = UILabel()
let minimumTemperatureLable: UILabel = UILabel()
let popLabel: UILabel = UILabel()
let humidityLabel: UILabel = UILabel()
let sunriseTimeLabel: UILabel = UILabel()
let sunsetTimeLabel: UILabel = UILabel()
let spacingView: UIView = UIView()
spacingView.backgroundColor = .clear
spacingView.setContentHuggingPriority(.defaultLow, for: .vertical)

Expand Down Expand Up @@ -92,7 +85,23 @@ class WeatherDetailViewController: UIViewController {
iconImageView.widthAnchor.constraint(equalTo: safeArea.widthAnchor,
multiplier: 0.3)
])

}
func setupData(){
guard let weatherInfo = delegate?.fetchWeatherInfo(),
let cityInfo = delegate?.fetchCityInfo(),
let tempUnit = delegate?.fetchTempUnit()
else { return }
updateWeatherInfo(listInfo: weatherInfo, tempUnit: tempUnit)
updateCityInfo(cityInfo)
updateWeatherIcon(iconName: weatherInfo.weather.icon)
}
gadisom marked this conversation as resolved.
Show resolved Hide resolved
}

extension WeatherDetailViewController {

func updateWeatherInfo(listInfo: WeatherForecastInfo, tempUnit: TempUnit){
let date: Date = Date(timeIntervalSince1970: listInfo.dt)
navigationItem.title = dateFormatter.string(from: date)
weatherGroupLabel.text = listInfo.weather.main
weatherDescriptionLabel.text = listInfo.weather.description
temperatureLabel.text = "현재 기온 : \(listInfo.main.temp)\(tempUnit.expression)"
Expand All @@ -101,27 +110,23 @@ class WeatherDetailViewController: UIViewController {
minimumTemperatureLable.text = "최저 기온 : \(listInfo.main.tempMin)\(tempUnit.expression)"
popLabel.text = "강수 확률 : \(listInfo.main.pop * 100)%"
humidityLabel.text = "습도 : \(listInfo.main.humidity)%"

if let cityInfo {
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = .none
formatter.timeStyle = .short
formatter.locale = .init(identifier: "ko_KR")
sunriseTimeLabel.text = "일출 : \(formatter.string(from: Date(timeIntervalSince1970: cityInfo.sunrise)))"
sunsetTimeLabel.text = "일몰 : \(formatter.string(from: Date(timeIntervalSince1970: cityInfo.sunset)))"
}

}
func updateWeatherIcon(iconName: String){
Task {
let iconName: String = listInfo.weather.icon
let urlString: String = "https://openweathermap.org/img/wn/\(iconName)@2x.png"

guard let url: URL = URL(string: urlString),
let (data, _) = try? await URLSession.shared.data(from: url),
let image: UIImage = UIImage(data: data) else {
return
if let iconImage = await NetworkService.shared.fetchWeatherIconImage(iconName: iconName) {
DispatchQueue.main.async {
self.iconImageView.image = iconImage
}
gadisom marked this conversation as resolved.
Show resolved Hide resolved
}

iconImageView.image = image
}
}
func updateCityInfo(_ cityInfo: City) {
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = .none
formatter.timeStyle = .short
formatter.locale = .init(identifier: "ko_KR")
sunriseTimeLabel.text = "일출 : \(formatter.string(from: Date(timeIntervalSince1970: cityInfo.sunrise)))"
sunsetTimeLabel.text = "일몰 : \(formatter.string(from: Date(timeIntervalSince1970: cityInfo.sunset)))"
}

}
30 changes: 29 additions & 1 deletion WeatherForecast/WeatherForecast/WeatherTableViewCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@ class WeatherTableViewCell: UITableViewCell {
var temperatureLabel: UILabel!
var weatherLabel: UILabel!
var descriptionLabel: UILabel!

var imageChache: NSCache<NSString, UIImage> = NSCache()
gadisom marked this conversation as resolved.
Show resolved Hide resolved

let dateFormatter: DateFormatter = {
let formatter: DateFormatter = DateFormatter()
formatter.locale = .init(identifier: "ko_KR")
formatter.dateFormat = "yyyy-MM-dd(EEEEE) a HH:mm"
return formatter
}()
gadisom marked this conversation as resolved.
Show resolved Hide resolved

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
layViews()
Expand Down Expand Up @@ -100,4 +108,24 @@ class WeatherTableViewCell: UITableViewCell {
weatherLabel.text = "~~~"
descriptionLabel.text = "~~~~~"
}
func configure(info: WeatherForecastInfo,tempUnit : TempUnit){
gadisom marked this conversation as resolved.
Show resolved Hide resolved
weatherLabel.text = info.weather.main
descriptionLabel.text = info.weather.description
temperatureLabel.text = "\(info.main.temp)\(tempUnit.expression)"
let date: Date = Date(timeIntervalSince1970: info.dt)
dateLabel.text = dateFormatter.string(from: date)
loadImage(info.weather.icon)
}
}
extension WeatherTableViewCell {

func loadImage(_ iconName: String){
Task {
if let iconImage = await NetworkService.shared.fetchWeatherIconImage(iconName: iconName) {
DispatchQueue.main.async {
self.weatherIcon.image = iconImage
}
}
}
}
}