Thanks, I had no idea this method existed, I'll play around with it.
Post
Replies
Boosts
Views
Activity
Thanks I'll check it out!
Thanks!!
Thanks that fixed the issue. I am experiencing another one though, related to the same function.
If I set the labels as you did with the String(format: "%.2f", lat) then the app will crash due to Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value but if I remove the formatting part, it doesn't crash.
Thanks, your comments helped out a lot. I think the main issue I was concerned with was whether or not I was using the right info in the completion handlers. It currently runs and doesn't throw any errors.
Next time I post a question I'll be sure to include more info, and thanks for the tip on line 47. I'll try that and see if anything changes.
Yeah that was an accident, I tried to fix it but I guess I can't.
I didn't have my API key in the proper place, it works now.
Thanks for the replies, I had to no idea URLComponents was a thing.
I've reformatted the code to look like this:
import UIKit
import CoreLocation
protocol APIManagerDelegate {
func didUpdateData(_ APIManager: APIManager, data: APIManager)
func didFailWithError(error: Error)
}
struct APIManager {
let dataURL = "https://api.openweathermap.org/data/2.5/weather?"
let appId = "appid="
let myApiKey = "..."
var delegate = APIManagerDelegate?.self
func fetchData(location: String) {
var urlComponents = URLComponents(string: dataURL)
urlComponents?.queryItems = [
URLQueryItem(name: "appId", value: appId),
URLQueryItem(name: "units", value: "imperial"),
URLQueryItem(name: "q", value: location),
]
performRequest(url: urlComponents?.url)
}
func performRequest(url: URL?) {
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
self.parseJSON(cityData: safeData)
}
}
task.resume()
}
}
func parseJSON(cityData: Data) {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(APIResults.self, from: cityData)
print(decodedData.name)
print(decodedData.main.temp)
print(decodedData.coord.lat)
print(decodedData.coord.lon)
} catch {
print(error)
}
}
}
however nothing is printing in the debug console, so I'm thinking there may still be a problem w/how the URL is being formatted. Is there something I'm missing/ not understanding?