-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformula.swift
54 lines (47 loc) · 1.7 KB
/
formula.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//
// Weather App (formula)
//
// Created by deathlezz on 16/08/2021.
//
// Targets -> Signing & Capabilities -> Location
// System Preferences -> Security & Privacy -> Enable Location Services
import CoreLocation
// specify how the JSON file looks like
struct Json: Codable {
let name: String
let main: [String: Double]
let wind: [String: Double]
}
// create function
func locationManager(_ manager: CLLocationManager, _ status: CLAuthorizationStatus) {
do {
// get user current location coordinates
let location = manager.location!.coordinate
// create url
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?lat=\(location.latitude)&lon=\(location.longitude)&appid={API key}")
// make http GET call
let contents = try String(contentsOf: url!)
// specify decoding format
let data = contents.data(using: .utf8)
// decode json data
let weatherData = try JSONDecoder().decode(Json.self, from: data!)
// output
print("City: \(weatherData.name)")
print("Temperature: \(weatherData.main["temp"]!) K")
print("Feels like: \(weatherData.main["feels_like"]!) K")
print("Wind: \(weatherData.wind["speed"]!) m/s")
print("Pressure: \(weatherData.main["pressure"]!) hPa")
print("Humidity: \(weatherData.main["humidity"]!) %")
} catch {
// error handling
print("* Some error occured *")
}
}
// enable location service
let manager = CLLocationManager()
// get user current location
manager.startUpdatingLocation()
// one second delay
sleep(1)
// call the function
locationManager(CLLocationManager(), CLAuthorizationStatus.authorized)