Swift JSON 天气问题

Posted

技术标签:

【中文标题】Swift JSON 天气问题【英文标题】:Swift JSON Weather issue 【发布时间】:2015-07-16 02:04:52 【问题描述】:

我实际上已经完成了我的应用程序的代码,但最后我正在尝试查找用户位置的天气。我从教程中借用了 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)
        
    


【问题讨论】:

【参考方案1】:

删除 URL 字符串中的大括号

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

【讨论】:

完全正确。甚至没有注意到,我只是认为它是正确的,因为它直接来自开放的天气站点。谢谢

以上是关于Swift JSON 天气问题的主要内容,如果未能解决你的问题,请参考以下文章

SwiftyJson 是不是可以更快地解析 swift json?

在 Swift 中存储天气预报数据

天气应用 (JSON) 数据未显示在文本视图中

使用 JSON 渲染数据(天气 API)

简单天气应用开发——解析HeWeather JSON

如何在 Swift 3 中将 NSData 转换为数据?