Reputation: 3
I'm trying to run an app that allows you to use a search bar and it'll return just temp, city, and conditions. When I run it I get a nil return on the temp and a 'Code: 401 API not valid' error. However, both codes I've tried should be working. I'm probably trying to take the wrong data from OpenWeather but I can't seem to find out where or how to fix it - there are no other errors that appear.
I'm trying to combine two tutorials/guides on this topic, but one uses a different API & the other is in Swift2.
Thanks!
import UIKit
class ViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var citySearchBar: UISearchBar!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var conditionLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
var temp: Int!
var condition: String!
var city: String!
let apiID:String = "d7817e07565a0019c5e7851a59eeca73"
var exists: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
citySearchBar.delegate = self
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let urlRequest = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(citySearchBar.text!.replacingOccurrences(of: " ", with: "_"))&appid=\(apiID))")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if error == nil {
do {
let weatherData = try JSONSerialization.jsonObject(
with: data!,
options: .mutableContainers) as! [String : AnyObject]
let weather = weatherData
DispatchQueue.main.async {
self.cityLabel.text = self.city
self.tempLabel.text = "\((self.temp))°"
self.conditionLabel.text = weather.description
}
} catch let jsonError {
print(jsonError.localizedDescription)
} } }
task.resume()
} }
Upvotes: 0
Views: 239
Reputation: 285069
First of all the value for temp
is a Double
not an Int
var temp = 0.0
Second of all you don't set temp
in the code. The value for temp
is in the dictionary main
in weatherData
if let main = weatherData["main"] as? [String:Any],
let tempValue = main["temp"] as? Double {
self.temp = tempValue
print(tempValue)
}
Upvotes: 1