Daily App part2

延續

接下來要抓一個天氣 API,但我們需要先取得到定位權限

https://openweathermap.org/api

專案底下 > Info 設定兩個值,Value 要填權限題問的標題

使用 Class 寫 API

class GetWeather {

static let apiKey = "4072d5043f1348fc21c6e9316302a015"
static let share = GetWeather()

func WeatherInfo (lon:String ,lat: String,completion: @escaping(Result<WeatherModel,Error>) -> Void){

let urlString = "https://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(lon)&appid=\(GetWeather.apiKey)&lang=zh_tw&units=metric"

guard let url = URL(string: urlString) else {return}

URLSession.shared.dataTask(with: url) { data , response, error in
if let data = data {
do {
let result = try JSONDecoder().decode(WeatherModel.self, from: data)
print(result)
completion(.success(result))
}catch{
completion(.failure(error))
}
}
}.resume()

}

}

在 Controller 需要設定定位的程式碼

import CoreLocation

var locationManager: CLLocationManager!

override func viewDidLoad() {
super.viewDidLoad()

// 初始化定位管理器
locationManager = CLLocationManager()
locationManager.delegate = self

// 請求定位權限
locationManager.requestWhenInUseAuthorization()

}

// 請求定位權限的回調方法
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
// 開始定位更新
locationManager.startUpdatingLocation()
}
}

// 接收定位更新的回調方法
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude

// 在這裡可以使用獲取到的經緯度進行相應的處理
print("緯度:\(latitude)")
print("經度:\(longitude)")

GetWeather.share.WeatherInfo(lon: "\(longitude)", lat: "\(latitude)") { result in
switch result {
case .success(let weather):
print(weather)
DispatchQueue.main.async {

self.getWeather(weather: weather)

}

case .failure(let error):
print(error)
}


}

// 獲取到所需的位置資訊後,停止定位更新
locationManager.stopUpdatingLocation()
}
}

// 處理定位錯誤的回調方法
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("定位錯誤:\(error.localizedDescription)")
}

func getWeather (weather: WeatherModel) {

guard let icon = weather.weather.first?.icon else{return}
guard let suffix = weather.weather.first?.icon.suffix(1) else {return}
weatherImage.image = UIImage(systemName: "photo")
let imageUrl = URL(string: "@2x.png">https://openweathermap.org/img/wn/\(icon)@2x.png")
URLSession.shared.dataTask(with: imageUrl!) { data , response, error in
if let data,
let image = UIImage(data: data) {
DispatchQueue.main.async {
self.weatherImage.image = image
self.dustrictName.text = weather.name
self.derscribetion.text = weather.weather[0].description
self.temp.text = "\(weather.main.temp)℃"
self.minTemp.text = "\(weather.main.temp_min)℃"
self.maxTemp.text = "\(weather.main.temp_max)℃"
self.humidity.text = "\(weather.main.humidity)%"
self.feelTemp.text = "\(weather.main.feels_like)℃ "

if (suffix == "n") {
self.view.backgroundColor = UIColor(red: 11/255, green: 72/255, blue: 108/255, alpha: 1)
self.changeLabelColorsIn(view: self.view, suffix: "n")
}else{
self.view.backgroundColor = UIColor(red: 36/255, green: 186/255, blue: 224/255, alpha: 1)
self.changeLabelColorsIn(view: self.view, suffix: "d")
}
}
}
}.resume()
}

//但這邊沒成功
func changeLabelColorsIn(view: UIView, suffix: String) {
for subview in view.subviews {
if let label = subview as? UILabel {
if let text = label.text, text.hasSuffix(suffix) {
label.textColor = (suffix == "n") ? UIColor.white : UIColor.black
}
} else {
changeLabelColorsIn(view: subview, suffix: suffix)
}
}
}

作品:

--

--