Я практически закончил код своего приложения, но наконец пытаюсь узнать погоду в месте расположения пользователя. Я позаимствовал код 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/ ... on={\(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)
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/314 ... ther-issue
Проблема с погодой в Swift JSON ⇐ IOS
Программируем под IOS
1737296936
Anonymous
Я практически закончил код своего приложения, но наконец пытаюсь узнать погоду в месте расположения пользователя. Я позаимствовал код 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)
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/31444228/swift-json-weather-issue[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия