简体   繁体   English

如何在我的天气API中放置placemark.locality?

[英]How to put placemark.locality in my weather API?

I am working on an app that gets your current location and then gives you the present weather conditions in your location (City). 我正在开发一个应用程序,该应用程序可获取您的当前位置,然后为您提供您所在位置(城市)的当前天气状况。

The app works successfully but only when I select which city the API should generate weather conditions for. 该应用程序成功运行,但仅当我选择API应为其生成天气条件的城市时才可运行。

I am able to get the users current city in the placemark.count, but i have not been able to put the placemark.count in my weather API url. 我可以在placemark.count中获取用户当前所在的城市,但是我无法将placemark.count放入我的天气API网址中。

Here is my full code: 这是我的完整代码:

import Foundation
import UIKit
import CoreLocation

class FirstViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    @IBOutlet weak var valueLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var temperature: UILabel!
    @IBOutlet weak var temperatureImage: UIImageView!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var maxTemp: UILabel!
    @IBOutlet weak var minTemp: UILabel!
    @IBOutlet weak var sunriseLabel: UILabel!
    @IBOutlet weak var sunsetLabel: UILabel!
    @IBOutlet weak var moonriseLabel: UILabel!
    @IBOutlet weak var moonsetLabel: UILabel!

    func clock() {
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: date)
        var hour = components.hour > 12 ? components.hour - 12 : components.hour

        hour = hour == 0 ? 12 : hour

        let hourString = hour > 9 ? "\(hour)" : "0\(hour)"
        let minutes = components.minute > 9 ? "\(components.minute)" : "0\(components.minute)"
        let seconds = components.second > 9 ? "\(components.second)" : "0\(components.second)"
        let am = components.hour > 12 ? "PM" : "AM"

        timeLabel.text = "\(hourString):\(minutes):\(seconds) \(am)"

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        super.viewDidLoad()

        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in

            if error != nil {
                println("Error: " + error.localizedDescription)
                return
            }

            if placemarks.count > 0 {
                let pm = placemarks[0] as! CLPlacemark
                self.displayLocationInfo(pm)
            }
        })
    }

    func displayLocationInfo(placemark: CLPlacemark) {
        self.locationManager.stopUpdatingLocation()

        println(placemark.locality)
        println(placemark.postalCode)
        println(placemark.administrativeArea)
        println(placemark.country)
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        println("Error: " + error.localizedDescription)
    }

    override  func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()

        var array : NSArray
        var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector ("clock") , userInfo: nil, repeats: true)

        timeLabel.text = ""
        self.timeLabel.alpha = 0

        temperature.text = ""
        self.temperature.alpha = 0

        maxTemp.text = ""
        self.maxTemp.alpha = -1

        minTemp.text = ""
        self.minTemp.alpha = 0

        sunriseLabel.text = ""
        self.sunriseLabel.alpha = 0

        sunsetLabel.text = ""
        self.sunsetLabel.alpha = 0

        moonriseLabel.text = ""
        self.moonriseLabel.alpha = 0
        moonsetLabel.text = ""
        self.moonsetLabel.alpha = 0

        self.temperatureImage.alpha = 0
        self.valueLabel.alpha = 0

        var myvariableOne = ""

        //myvariable = myvariableOne

        var key = “**mykey**"
        var urladd1 = "http://api.worldweatheronline.com/free/v2/weather.ashx?q="
        var urlString2 = "Lagos"
        var urlString3 = "&format=json&num_of_days=1&key="
        var urlString = urladd1 + urlString2 + urlString3 + key

        println(urlString)

        cityLabel.text = urlString2
        self.cityLabel.alpha = 0

        let url = NSURL(string: urlString)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
            if error != nil {
                println(error)
            } else {
                // weather info loading
                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
                let mainObject: NSDictionary = jsonResult.objectForKey("data") as! NSDictionary
                print(mainObject)

                let currentConditions: NSArray = mainObject.objectForKey("current_condition") as! NSArray
                let icon: NSArray = currentConditions[0]["weatherIconUrl"] as! NSArray
                let iconPath: AnyObject? = icon[0]["value"]
                let iconRequest = NSURLRequest(URL: NSURL(string: "\(iconPath!)")!)

                var image: UIImage?

                NSURLConnection.sendAsynchronousRequest(iconRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { ( response: NSURLResponse!, imageData: NSData!, error: NSError!) -> Void in
                    image = UIImage(data: imageData)
                    self.temperatureImage.image = image
                })

                let currentTemperature: AnyObject? = currentConditions[0]["temp_C"]
                self.temperature.text = "\(currentTemperature!) ℃"
                let weather: NSArray = mainObject.objectForKey("weather") as! NSArray
                let weatherDictionary: NSDictionary = weather.objectAtIndex(0) as! NSDictionary
                let astronomyArray: NSArray = weatherDictionary.objectForKey("astronomy") as! NSArray
                let moonriseTime: AnyObject? = astronomyArray[0]["moonrise"]

                self.moonriseLabel.text = "\(moonriseTime!)"
                let moonsetTime: AnyObject? = astronomyArray[0]["moonset"]
                self.moonsetLabel.text = "\(moonsetTime!)"
                let sunriseTime: AnyObject? = astronomyArray[0]["sunrise"]
                self.sunriseLabel.text = "\(sunriseTime!)"
                let sunsetTime : AnyObject? = astronomyArray[0]["sunset"]
                self.sunsetLabel.text = "\(sunsetTime!)"
                let maxTemp: AnyObject? = weatherDictionary.objectForKey("maxtempC")
                self.maxTemp.text = "\(maxTemp!) ℃"
                let minTemp: AnyObject? = weatherDictionary.objectForKey("mintempC")
                self.minTemp.text = "\(minTemp!) ℃"
            }
        })

        task.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        UIView.animateWithDuration(5.0, animations: { () -> Void in
            self.timeLabel.alpha = 2.0
            self.temperature.alpha = 5.0
            self.maxTemp.alpha = 2.0
            self.minTemp.alpha = 2.0
            self.sunriseLabel.alpha = 2.0
            self.sunsetLabel.alpha = 2.0
            self.moonriseLabel.alpha = 2.0
            self.moonsetLabel.alpha = 2.0
            self.cityLabel.alpha = 2.0
            self.temperatureImage.alpha = 5.0
            self.valueLabel.alpha = 5.0
        })
    }
}

I would suggest the following course of action: 我建议采取以下行动:

First create a function that will handle all your request, you can pass the city you want as an argument: 首先创建一个将处理所有请求的函数,您可以将所需的城市作为参数传递:

func getWeatherFromCity(city: String) {
        var key = “**mykey**"
        var urladd1 = "http://api.worldweatheronline.com/free/v2/weather.ashx?q="
        var urlString2 = city
        var urlString3 = "&format=json&num_of_days=1&key="
        var urlString = urladd1 + urlString2 + urlString3 + key

        println(urlString)

        cityLabel.text = urlString2
        self.cityLabel.alpha = 0

        let url = NSURL(string: urlString)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
            if error != nil {
                println(error)
            } else {
                // weather info loading
                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
                let mainObject: NSDictionary = jsonResult.objectForKey("data") as! NSDictionary
                print(mainObject)

                let currentConditions: NSArray = mainObject.objectForKey("current_condition") as! NSArray
                let icon: NSArray = currentConditions[0]["weatherIconUrl"] as! NSArray
                let iconPath: AnyObject? = icon[0]["value"]
                let iconRequest = NSURLRequest(URL: NSURL(string: "\(iconPath!)")!)

                var image: UIImage?

                NSURLConnection.sendAsynchronousRequest(iconRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { ( response: NSURLResponse!, imageData: NSData!, error: NSError!) -> Void in
                    image = UIImage(data: imageData)
                    self.temperatureImage.image = image
                })

                let currentTemperature: AnyObject? = currentConditions[0]["temp_C"]
                self.temperature.text = "\(currentTemperature!) ℃"
                let weather: NSArray = mainObject.objectForKey("weather") as! NSArray
                let weatherDictionary: NSDictionary = weather.objectAtIndex(0) as! NSDictionary
                let astronomyArray: NSArray = weatherDictionary.objectForKey("astronomy") as! NSArray
                let moonriseTime: AnyObject? = astronomyArray[0]["moonrise"]

                self.moonriseLabel.text = "\(moonriseTime!)"
                let moonsetTime: AnyObject? = astronomyArray[0]["moonset"]
                self.moonsetLabel.text = "\(moonsetTime!)"
                let sunriseTime: AnyObject? = astronomyArray[0]["sunrise"]
                self.sunriseLabel.text = "\(sunriseTime!)"
                let sunsetTime : AnyObject? = astronomyArray[0]["sunset"]
                self.sunsetLabel.text = "\(sunsetTime!)"
                let maxTemp: AnyObject? = weatherDictionary.objectForKey("maxtempC")
                self.maxTemp.text = "\(maxTemp!) ℃"
                let minTemp: AnyObject? = weatherDictionary.objectForKey("mintempC")
                self.minTemp.text = "\(minTemp!) ℃"
            }
        })

        task.resume()
}

In your viewDidLoad you can call this function with "Lagos as an argument viewDidLoad您可以使用“拉各斯作为参数来调用此函数

override  func viewDidLoad() {
    super.viewDidLoad()
    ...
    getWeatherFromCity("Lagos)
}

finally in your locationManager(_ didUpdateLocations locations: _) , you can call this same function when you have received your location: 最后,在您的locationManager(_ didUpdateLocations locations: _) ,可以在收到位置信息后调用相同的函数:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        super.viewDidLoad()

        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in

            if error != nil {
                println("Error: " + error.localizedDescription)
                return
            }

            if placemarks.count > 0 {
                let pm = placemarks[0] as! CLPlacemark
                self.displayLocationInfo(pm)
                getWeatherFromCity(pm.locality)
            }
        })
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM