gpt4 book ai didi

ios - Swift JSON 天气问题

转载 作者:行者123 更新时间:2023-11-28 09:03:30 24 4
gpt4 key购买 nike

我几乎已经完成了我的应用程序的代码,但最后我要尝试查找用户所在位置的天气。我从教程中借用了 JSON 代码并稍作修改,但它不起作用。

根据调试器,getWeatherData 函数传递了正确的 url 以从 openweathermap 获取我想要的信息,但“url”显示为 nil,我不明白。有人知道我做错了什么吗?

import UIKit
import MapKit

class MapController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBAction func fetchWeather(sender: AnyObject) {

var lat = manager.location.coordinate.latitude
var lon = manager.location.coordinate.longitude

getWeatherData("http://api.openweathermap.org/data/2.5/weather?lat={\(lat)}&lon={\(lon)}")
}

@IBAction func removeAnno(sender: AnyObject) {
let annotationsToRemove = mapView.annotations.filter { $0 !== self.mapView.userLocation }
mapView.removeAnnotations( annotationsToRemove )
distanceLabel.text = " "
}

@IBOutlet weak var cityTempLabel: UILabel!

@IBOutlet weak var cityNameLabel: UILabel!

@IBOutlet weak var mapView: MKMapView!

@IBOutlet weak var distanceLabel: UILabel!

var manager:CLLocationManager!
var myLocations: [CLLocation] = []

override func viewDidLoad() {
super.viewDidLoad()

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "deerscopebackground.jpg")!)

//Setup our Location Manager
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()

//Setup our Map View
mapView.delegate = self
mapView.mapType = MKMapType.Satellite
mapView.showsUserLocation = true

let longPress = UILongPressGestureRecognizer(target: self, action: "action:")
longPress.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPress)

}

func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {

myLocations.append(locations[0] as! CLLocation)

let spanX = 0.007
let spanY = 0.007
var newRegion = MKCoordinateRegion(center: mapView.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
mapView.setRegion(newRegion, animated: true)

}

func action(gesture:UIGestureRecognizer) {

var touchPoint = gesture.locationInView(self.mapView)
var newCoord:CLLocationCoordinate2D = mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)

var newAnotation = MKPointAnnotation()
newAnotation.coordinate = newCoord

mapView.addAnnotation(newAnotation)

if (gesture.state == UIGestureRecognizerState.Ended) {
println("Long press Ended");
}
else if (gesture.state == UIGestureRecognizerState.Began) {
println("Long press detected.");
var distance = 0.0
var roundDistance = 0.0
let DEG_TO_RAD = 0.017453292519943295769236907684886;
let EARTH_RADIUS_IN_METERS = 6372797.560856;

var latitudeArc = (manager.location.coordinate.latitude - newCoord.latitude) * DEG_TO_RAD
var longitudeArc = (manager.location.coordinate.longitude - newCoord.longitude) * DEG_TO_RAD
var latitudeH = sin(latitudeArc * 0.5)
latitudeH *= latitudeH
var lontitudeH = sin(longitudeArc * 0.5)
lontitudeH *= lontitudeH
var tmp = cos(manager.location.coordinate.latitude*DEG_TO_RAD) * cos(newCoord.latitude*DEG_TO_RAD)
distance = EARTH_RADIUS_IN_METERS * 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH))
roundDistance = round(distance)
println("\(distance)")
println("\(roundDistance)")
distanceLabel.text = "\(roundDistance) m"
}
}

func getWeatherData(urlString: String) {

let url = NSURL(string: urlString)

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.setLabels(data)
})

}
task.resume()
}

func setLabels(weatherData: NSData) {

var jsonError: NSError?

let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: &jsonError) as! NSDictionary

if let name = json["name"] as? String {
cityNameLabel.text = name
}

if let main = json["main"] as? NSDictionary {
if let temp = main["temp"] as? Double {
cityTempLabel.text = String(format: "%.1f", temp)
}
}

}

最佳答案

去掉URL字符串中的大括号

getWeatherData("http://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(lon)")

关于ios - Swift JSON 天气问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31444228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com