Swift JSON 天气问题

问题描述 投票:0回答:1

我实际上已经完成了应用程序的代码,但最后我试图查找用户位置的天气。我借用了教程中的 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)
            }
        }
        
    }    
}
ios json swift openweathermap
1个回答
0
投票

删除 URL 字符串中的大括号

getWeatherData("http://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(lon)")
© www.soinside.com 2019 - 2024. All rights reserved.