如何将 placemark.locality 放入我的天气 API?
Posted
技术标签:
【中文标题】如何将 placemark.locality 放入我的天气 API?【英文标题】:How to put placemark.locality in my weather API? 【发布时间】:2015-06-26 03:08:48 【问题描述】:我正在开发一个应用程序,它可以获取您当前的位置,然后为您提供您所在位置(城市)的当前天气状况。
只有当我选择 API 应该为哪个城市生成天气条件时,该应用才能成功运行。
我能够在 placemark.count 中获取用户当前的城市,但我无法将 placemark.count 放入我的天气 API url。
这是我的完整代码:
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
)
【问题讨论】:
对不起,我的代码有点分散,但这就是所有代码。我要放入的完整 Url 字符串是 viewDidLoad() 中的变量“urlString”。另请注意,“Mykey*”是我不想透露的私有 API 密钥 【参考方案1】:我建议采取以下行动:
首先创建一个函数来处理你的所有请求,你可以将你想要的城市作为参数传递:
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()
在您的viewDidLoad
中,您可以使用“Lagos 作为参数”调用此函数
override func viewDidLoad()
super.viewDidLoad()
...
getWeatherFromCity("Lagos)
最后在你的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)
)
【讨论】:
我明白你在说什么,但你仍然没有告诉我如何将我从 locationManager 函数获得的城市传递到名为 urlString2 的变量中,这样它将完成变量 urlString 并生成天气API 中的那个城市。例如,如果 locationManager 在 placemark.locality 中生成一个名为 New York 的城市。如果我在纽约传递到 urlString2,则 urlString 现在将变为 api.worldweatheronline.com/free/v2/…**mykey** 。此 url 将生成纽约的天气状况。谢谢。 我编辑了我的答案来回答这个问题。在您的函数中,您必须像这样将参数分配给 urlString2: var urlString2 = city 我还没有尝试过这段代码,但我确信它会根据我的分析工作。谢谢。无论如何我可以与您联系吗?我认为我们都将 ios 应用程序编程作为一种爱好。谢谢 欢迎在 Twitter 上与我联系,用户名在个人资料中 我刚刚在推特上关注了你。以上是关于如何将 placemark.locality 放入我的天气 API?的主要内容,如果未能解决你的问题,请参考以下文章