Swift JSON天气问题

时间:2015-07-16 02:04:53

标签: ios json swift api

我已经为我的应用程序虚拟完成了代码但最终我试图在用户位置找到天气。我从教程中借用了JSON代码并对其进行了一些修改,但它不起作用。

getWeatherData函数传递正确的url,根据调试器从openweathermap获取我想要的信息,但是" url"显示为零,我不明白。谁知道我做错了什么?

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)
        }
    }

}

}

1 个答案:

答案 0 :(得分:0)

删除网址字符串

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