· 7 years ago · Nov 29, 2018, 09:54 PM
1
2import Foundation
3
4struct Weather{
5 let summary:String
6 let icon:String
7 let temperatureMin:Double
8 let temperatureMax: Double
9 let windSpeed: Double
10 let windDirection: Double
11 let pressure: Double
12 let dewPoint: Double // rain probability
13
14 enum SerializationError:Error {
15 case missing(String)
16 case invalid(String, Any)
17 }
18
19// https://api.darksky.net/forecast/965b5e1f6514ee3a66017c215d128973/42.3601,-71.0589,255657600?units=si&exclude=currently,minutely,hourly,alerts,flags
20init(json:[String:Any]) throws {
21 guard let summary = json["summary"] as? String else {throw SerializationError.missing("Summary is missing")}
22 guard let icon = json["icon"] as? String else {throw SerializationError.missing("icon is missing")}
23 guard let temperatureMin = json["temperatureMin"] as? String else {throw SerializationError.missing("temperatureMin is missing")}
24 guard let temperatureMax = json["temperatureMax"] as? String else {throw SerializationError.missing("temperatureMax is missing")}
25 guard let windSpeed = json["windSpeed"] as? String else {throw SerializationError.missing("windSpeed is missing")}
26 guard let windDirection = json["windBearing"] as? String else {throw SerializationError.missing("windBearing is missing")}
27 guard let dewPoint = json["dewPoint"] as? String else {throw SerializationError.missing("dewPoint is missing")}
28
29 self.summary = summary
30 self.icon = icon
31 self.temperatureMin = temperatureMin
32 self.temperatureMax = temperatureMax
33 self.windSpeed = windSpeed
34 self.windDirection = windDirection
35 self.pressure = pressure
36 self.dewPoint = dewPoint
37 }
38
39 static let basePath = "https://api.darksky.net/forecast/"
40 static let secretKey = "965b5e1f6514ee3a66017c215d128973"
41
42 static func forecast (withLocation location:String, completion: @escaping ([Weather]) -> ()) {
43 let url = basePath + secretKey + "/" + location
44 let request = URLRequest(url: URL(string: url)!)
45
46 let task = URLSession.shared.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in
47
48 var forecastArray:[Weather] = []
49
50 if let data = data {
51 do {
52 if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
53 if let dailyForecasts = json["daily"] as? [String:Any] {
54 if let dailyData = dailyForecasts["data"] as? [[String:Any]] {
55 for dataPoint in dailyData {
56 if let weatherObject = try? Weather(json: dataPoint) {
57 forecastArray.append(weatherObject)
58 }
59 }
60 }
61 }
62 }
63 } catch {
64 print(error.localizedDescription)
65 }
66
67 completion(forecastArray)
68 }
69
70
71 }
72
73 task.resume()
74 }
75}
76
77
78
79
80
81import UIKit
82
83class ViewController: UIViewController {
84 override fun viewDidLoad() {
85 super.viewDidLoad
86
87 Weather.forecast(withLocation: "37.8267,-122.4233") { (results:[Weather]) in
88 for result in results {
89 print("\(result)\n\n")
90 }
91 }
92 }
93}