Skip to content
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
4 changes: 4 additions & 0 deletions SwiftStyle/Rainy/Rainy.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
025F4DC31FA32DAE00635F83 /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 025F4DC21FA32DAE00635F83 /* Constants.swift */; };
7B11FC3E1DB53A6900FA6122 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B11FC3D1DB53A6900FA6122 /* AppDelegate.swift */; };
7B11FC401DB53A6900FA6122 /* CurrentWeatherViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B11FC3F1DB53A6900FA6122 /* CurrentWeatherViewController.swift */; };
7B11FC421DB53A6900FA6122 /* HomeWeatherViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B11FC411DB53A6900FA6122 /* HomeWeatherViewController.swift */; };
Expand All @@ -22,6 +23,7 @@
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
025F4DC21FA32DAE00635F83 /* Constants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Constants.swift; sourceTree = "<group>"; };
7B11FC3A1DB53A6900FA6122 /* Rainy.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Rainy.app; sourceTree = BUILT_PRODUCTS_DIR; };
7B11FC3D1DB53A6900FA6122 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7B11FC3F1DB53A6900FA6122 /* CurrentWeatherViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CurrentWeatherViewController.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -77,6 +79,7 @@
7B11FC3C1DB53A6900FA6122 /* Rainy */ = {
isa = PBXGroup;
children = (
025F4DC21FA32DAE00635F83 /* Constants.swift */,
7B11FC3D1DB53A6900FA6122 /* AppDelegate.swift */,
7B11FC3F1DB53A6900FA6122 /* CurrentWeatherViewController.swift */,
7B11FC411DB53A6900FA6122 /* HomeWeatherViewController.swift */,
Expand Down Expand Up @@ -249,6 +252,7 @@
7B11FC3E1DB53A6900FA6122 /* AppDelegate.swift in Sources */,
7B11FC401DB53A6900FA6122 /* CurrentWeatherViewController.swift in Sources */,
7B6469FB1DC643AE00AA44F2 /* SettingsViewController.swift in Sources */,
025F4DC31FA32DAE00635F83 /* Constants.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
36 changes: 36 additions & 0 deletions SwiftStyle/Rainy/Rainy/Constants.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//
// Constants.swift
// Rainy
//
// Created by di on 27.10.2017.
// Copyright © 2017 Kirill Averyanov. All rights reserved.
//

import Foundation
import UIKit

struct Resources {
static let weatherURL = "http://api.openweathermap.org/data/2.5/weather"
static let trafficURL = "http://www.mapquestapi.com/traffic/v2/incidents"
}

let photoResources: [String: UIImage] = [
"01d":#imageLiteral(resourceName: "sunny"),
"01n":#imageLiteral(resourceName: "moon"),
"02d":#imageLiteral(resourceName: "sunny_clouds"),
"02n":#imageLiteral(resourceName: "moodCloud"),
"03d":#imageLiteral(resourceName: "clouds"),
"03n":#imageLiteral(resourceName: "clouds"),
"04d":#imageLiteral(resourceName: "clouds"),
"04n":#imageLiteral(resourceName: "clouds"),
"09d":#imageLiteral(resourceName: "cloud_rain"),
"09n":#imageLiteral(resourceName: "cloud_rain"),
"10d":#imageLiteral(resourceName: "sunCloudRain"),
"10n":#imageLiteral(resourceName: "moonrain"),
"11d":#imageLiteral(resourceName: "storm"),
"11n":#imageLiteral(resourceName: "storm"),
"13d":#imageLiteral(resourceName: "CloudSnow"),
"13n":#imageLiteral(resourceName: "CloudSnow"),
"50d":#imageLiteral(resourceName: "fog"),
"50n":#imageLiteral(resourceName: "fog")
]
245 changes: 113 additions & 132 deletions SwiftStyle/Rainy/Rainy/CurrentWeatherViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,156 +13,137 @@ import SwiftyJSON



struct coords{
var lat: Double = 0
var lon: Double = 0
struct coords {
var lat: Double = 0
var lon: Double = 0
}

class CurrentWeatherViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var windLabel: UILabel!
@IBOutlet weak var cityNameLabel: UILabel!
@IBOutlet weak var imageWeather: UIImageView!

private var locationManager: CLLocationManager!
// private let constrain: Constants = Constants()
private var currentForecast: WeatherForecast? {
didSet{
reloadUI()
}
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var windLabel: UILabel!
@IBOutlet weak var cityNameLabel: UILabel!
@IBOutlet weak var imageWeather: UIImageView!

private var locationManager: CLLocationManager!
private var currentForecast: WeatherForecast? {
didSet{
reloadUI()
}
}

private var myCoords: coords = coords()

override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
if(CLLocationManager.authorizationStatus() == .notDetermined) {
locationManager.requestWhenInUseAuthorization()
}

private let photoResources: [String: UIImage] = [
"01d":#imageLiteral(resourceName: "sunny"),
"01n":#imageLiteral(resourceName: "moon"),
"02d":#imageLiteral(resourceName: "sunny_clouds"),
"02n":#imageLiteral(resourceName: "moodCloud"),
"03d":#imageLiteral(resourceName: "clouds"),
"03n":#imageLiteral(resourceName: "clouds"),
"04d":#imageLiteral(resourceName: "clouds"),
"04n":#imageLiteral(resourceName: "clouds"),
"09d":#imageLiteral(resourceName: "cloud_rain"),
"09n":#imageLiteral(resourceName: "cloud_rain"),
"10d":#imageLiteral(resourceName: "sunCloudRain"),
"10n":#imageLiteral(resourceName: "moonrain"),
"11d":#imageLiteral(resourceName: "storm"),
"11n":#imageLiteral(resourceName: "storm"),
"13d":#imageLiteral(resourceName: "CloudSnow"),
"13n":#imageLiteral(resourceName: "CloudSnow"),
"50d":#imageLiteral(resourceName: "fog"),
"50n":#imageLiteral(resourceName: "fog")]


private var myCoords: coords = coords()


override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
if(CLLocationManager.authorizationStatus() == .notDetermined){
locationManager.requestWhenInUseAuthorization()
}

if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
self.updateCurrentForecast()
})
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}

@IBAction func reloadButtonPressed(_ sender: AnyObject) {
if(CLLocationManager.authorizationStatus() == .notDetermined){
locationManager.requestWhenInUseAuthorization()
}

if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
updateCurrentForecast()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
self.updateCurrentForecast()
})
}

@IBAction func reloadButtonPressed(_ sender: AnyObject) {
if(CLLocationManager.authorizationStatus() == .notDetermined) {
locationManager.requestWhenInUseAuthorization()
}


internal func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
print("error: ", error)
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}

internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.myCoords.lat = locations[0].coordinate.latitude
self.myCoords.lon = locations[0].coordinate.longitude
locationManager.stopUpdatingLocation()
updateCurrentForecast()
}


internal func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
print("error: ", error)
}

internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.myCoords.lat = locations[0].coordinate.latitude
self.myCoords.lon = locations[0].coordinate.longitude
locationManager.stopUpdatingLocation()
}


private func updateCurrentForecast(){
Alamofire.request(Resources.weatherURL, method: .get,parameters: ["lat":myCoords.lat,"lon": myCoords.lon,"APPID": "","units":"metric"],encoding: JSONEncoding.default,headers: nil).responseJSON { response in

guard response.result.isSuccess else {
return
}

let json = JSON(response.result.value!)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Force unwrap

self.currentForecast = WeatherForecast(currentWeatherTempurature: round(10 * json["main"]["temp"].doubleValue) / 10,
timeStamp: self.getCurrentTime(),
imageName: json["weather"][0]["icon"].string ?? "",
locationCoordinates: (self.myCoords.lat, self.myCoords.lon),
humidity: json["main"]["humidity"].int,
pressure: json["main"]["pressure"].int,
wind: round(10 * json["wind"]["speed"].doubleValue) / 10, cityName: json["name"].string,
stateWeather: json["weather"][0]["description"].string)
}


private func updateCurrentForecast(){
Alamofire.request("http://api.openweathermap.org/data/2.5/weather",method: .get,parameters: ["lat":myCoords.lat,"lon": myCoords.lon,"APPID": "","units":"metric"],encoding: JSONEncoding.default,headers: nil).responseJSON{response in
guard response.result.isSuccess else{
return
}
let json = JSON(response.result.value!)
self.currentForecast = WeatherForecast(currentWeatherTempurature: round(10 * json["main"]["temp"].doubleValue) / 10,
timeStamp: self.getCurrentTime(),
imageName: json["weather"][0]["icon"].string!,
locationCoordinates: (self.myCoords.lat, self.myCoords.lon),
humidity: json["main"]["humidity"].int,
pressure: json["main"]["pressure"].int,
wind: round(10 * json["wind"]["speed"].doubleValue) / 10, cityName: json["name"].string,
stateWeather: json["weather"][0]["description"].string)
}

private func getTrafficInformation(){
let parameters = ["boundingBox": "\(myCoords.lat),\(myCoords.lon),\(myCoords.lat - 1),\(myCoords.lon - 1)", "key": ""]
Alamofire.request(Resources.trafficURL, parameters: parameters)
.responseJSON{response in
guard response.result.isSuccess else{
return
}
_ = JSON(response.result.value!)
}
}

private func getCurrentTime() -> String{
let date = NSDate()
let calendar = NSCalendar.current
var currentTime: String
let components = calendar.dateComponents([.hour, .minute], from: date as Date)
var hour: String = String(describing: components.hour ?? 0)
var minute: String = String(describing: components.minute ?? 0)

private func getTrafficInformation(){
Alamofire.request("http://www.mapquestapi.com/traffic/v2/incidents",
parameters: ["boundingBox": "\(myCoords.lat),\(myCoords.lon),\(myCoords.lat - 1),\(myCoords.lon - 1)",
"key": ""])
.responseJSON{response in
guard response.result.isSuccess else{
return
}
_ = JSON(response.result.value!)
}
if hour.characters.count == 1 {
hour = "0" + hour
}

private func getCurrentTime() -> String{
let date = NSDate()
let calendar = NSCalendar.current
var currentTime: String
let components = calendar.dateComponents([.hour, .minute], from: date as Date!)
var hour: String = String(describing: components.hour!)
var minute: String = String(describing: components.minute!)
if hour.characters.count == 1{
hour = "0" + hour
}
if(minute.characters.count == 1){
minute = "0" + minute
}
currentTime = "\(hour):\(minute)"
return currentTime
if(minute.characters.count == 1){
minute = "0" + minute
}



private func reloadUI(){
timeLabel.text = "Updated: \(currentForecast!.timeStamp)"
if let temp = currentForecast?.currentWeatherTempurature{
temperatureLabel.text = "\(temp)℃"
}
if let city = currentForecast?.cityName{
cityNameLabel.text = city
}
if let wi = currentForecast?.wind{
windLabel.text = "\(wi)"
}
if let st = currentForecast?.stateWeather{
stateLabel.text = st
}
imageWeather.image = photoResources[(currentForecast?.imageName)!]
currentTime = "\(hour):\(minute)"
return currentTime
}



private func reloadUI(){
timeLabel.text = "Updated: \(currentForecast!.timeStamp)"
if let temp = currentForecast?.currentWeatherTempurature {
temperatureLabel.text = "\(temp)℃"
}
if let city = currentForecast?.cityName {
cityNameLabel.text = city
}
if let wi = currentForecast?.wind {
windLabel.text = "\(wi)"
}
if let st = currentForecast?.stateWeather {
stateLabel.text = st
}
imageWeather.image = photoResources[(currentForecast?.imageName)!]
}
}


Loading