["?xml": {
"#encoding" = "utf-8";
"#version" = "1.0";
}, "root": {
"#id" = 1;
date = "11/25/2018";
message = "";
station = (
{
abbr = 24TH;
etd = (
{
abbreviation = ANTC;
destination = Antioch;
estimate = (
{
bikeflag = 1;
color = YELLOW;
delay = 86;
direction = North;
hexcolor = "#ffff33";
length = 10;
minutes = 4;
platform = 2;
},
{
bikeflag = 1;
color = YELLOW;
delay = 0;
direction = North;
hexcolor = "#ffff33";
length = 10;
minutes = 23;
platform = 2;
},
{
bikeflag = 1;
color = YELLOW;
delay = 0;
direction = North;
hexcolor = "#ffff33";
length = 10;
minutes = 43;
platform = 2;
}
);
limited = 0;
},
{
abbreviation = DALY;
destination = "Daly City";
estimate = (
{
bikeflag = 1;
color = BLUE;
delay = 214;
direction = South;
hexcolor = "#0099cc";
length = 9;
minutes = 11;
platform = 1;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = South;
hexcolor = "#0099cc";
length = 9;
minutes = 27;
platform = 1;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = South;
hexcolor = "#0099cc";
length = 9;
minutes = 47;
platform = 1;
}
);
limited = 0;
},
{
abbreviation = DUBL;
destination = "Dublin/Pleasanton";
estimate = (
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = North;
hexcolor = "#0099cc";
length = 9;
minutes = 10;
platform = 2;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = North;
hexcolor = "#0099cc";
length = 9;
minutes = 30;
platform = 2;
},
{
bikeflag = 1;
color = BLUE;
delay = 0;
direction = North;
hexcolor = "#0099cc";
length = 9;
minutes = 50;
platform = 2;
}
);
limited = 0;
},
{
abbreviation = MLBR;
destination = "SFO/Millbrae";
estimate = (
{
bikeflag = 1;
color = YELLOW;
delay = 245;
direction = South;
hexcolor = "#ffff33";
length = 10;
minutes = 17;
platform = 1;
},
{
bikeflag = 1;
color = YELLOW;
delay = 254;
direction = South;
hexcolor = "#ffff33";
length = 10;
minutes = 38;
platform = 1;
},
{
bikeflag = 1;
color = YELLOW;
delay = 0;
direction = South;
hexcolor = "#ffff33";
length = 10;
minutes = 53;
platform = 1;
}
);
limited = 0;
}
);
name = "24th St. Mission";
}
);
time = "05:28:01 PM PST";
uri = {
"#cdata-section" = "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=24TH&json=y";
};
}]
Want to get abbr, abbreviation, minutes in three separate arrays. So the root is a separate element as in, key1 = xml and key2 = root.
this is what I have. I am getting till estimates array but not able to get the values like I mentioned before.
static func singleRoute(_ station: String?, completionHandler: #escaping (SingleRouteModel?) -> Void) {
let routeURL = URL(string: "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=\(station ?? "12TH")&key=MW9S-E7SL-26DU-VV8V&json=y")
var routeModel = SingleRouteModel()
URLSession.shared.dataTask(with: routeURL!) { (data, response, error) in
if error == nil {
do {
guard let todo = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers)
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
print("todo = \(todo)")
let root = todo["root"] as? [String: Any]
let station = root?["station"] as? [[String: Any]]
var etd: [[String : Any]]?
var estimate: Any?
for (_, value) in (station?.enumerated())! {
etd = value["etd"] as? [[String: Any]]
}
var estimates: [String: Any]? = [:]
if let etd = etd {
for (key, value) in etd.enumerated() {
estimates?["\(key)"] = value
}
} else {
completionHandler(nil)
}
if let estimate = estimates {
for (k, v) in estimate {
print(v)
}
}
completionHandler(routeModel)
} catch {
print("error trying to convert data to JSON")
return
}
} else {
print("no data")
}
}.resume()
}
Here's the code in Playground form:
import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
struct Estimate: Codable {
let minutes: String
}
struct ETD: Codable {
let abbreviation: String
let estimate: [Estimate]
}
struct Station: Codable {
let abbr: String
let etd: [ETD]
}
struct Root: Codable {
let station: [Station]
}
struct SingleRouteModel: Codable {
let root: Root
}
func singleRoute(_ station: String?, completionHandler: #escaping (SingleRouteModel?) -> Void) {
let routeURL = URL(string: "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=\(station ?? "12TH")&key=MW9S-E7SL-26DU-VV8V&json=y")
URLSession.shared.dataTask(with: routeURL!) { (data, response, error) in
if let data = data {
let model = try? JSONDecoder().decode(SingleRouteModel.self, from: data)
completionHandler(model)
}
else {
completionHandler(nil)
}
}.resume()
}
singleRoute(nil, completionHandler: { model in
guard let model = model else { print("failed"); return }
let abbrs = model.root.station
.map { $0.abbr }
let abbreviations = model.root.station
.flatMap { $0.etd }
.flatMap { $0.abbreviation }
let minutes = model.root.station
.flatMap { $0.etd }
.flatMap { $0.estimate }
.map { $0.minutes }
print("abbrs:", abbrs)
print("abbreviations:", abbreviations)
print("minutes:", minutes)
})
Related
I am new to swift/spritekit, i was asked by my 8 year old to make him a basic game so i said yes (almost regretting it now lol)
What i am trying to achieve: a character who has the ability to "level up" based off experience points earned - I am using a JSON file to describe the levels
JSON file:
[
{
"id": 1,
"spriteTexture": "playerL1",
"weapon": "playerL1Weapon",
"expToLvlUp": 50,
"health": 2,
"attack": 1,
"defense": 1,
},
{
"id": 2,
"spriteTexture": "playerL2",
"weapon": "playerL2Weapon",
"expToLvlUp": 60,
"health": 7,
"attack": 2,
"defense": 2,
},
{
"id": 3,
"spriteTexture": "playerL3",
"weapon": "playerL3Weapon",
"expToLvlUp": 100,
"health": 10,
"attack": 5,
"defense": 5,
}
]
Decodable file:
import Foundation
extension Bundle{
func decode<T: Decodable>(_ Type: T.Type, from file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle")
}
guard let data = try? Data(contentsOf: url) else{
fatalError("Failed to load \(file) from bundle")
}
let decoder = JSONDecoder()
guard let loaded = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode /(file) from bundle")
}
return loaded
}
}
I have set up a struct to get the values from the JSON file:
import SpriteKit
struct PlayerLevel: Codable {
let id: Int
let spriteTexture: String
let weapon: String
let expToLvlUp: Int
let health: Int
let attack: Int
let defense: Int
}
and here is my class:
import Foundation
import SpriteKit
class Player: SKSpriteNode {
var type: PlayerLevel
{
didSet{
levelUp()
}
}
init(type: PlayerLevel){
self.type = type
let texture = SKTexture(imageNamed: type.spriteTexture)
super.init(texture: texture, color: .clear, size: texture.size())
position.x = -900
physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
physicsBody?.categoryBitMask = CollisionType.player.rawValue
physicsBody?.collisionBitMask = CollisionType.enemy.rawValue | CollisionType.enemyWeapon.rawValue
physicsBody?.contactTestBitMask = CollisionType.enemy.rawValue | CollisionType.enemyWeapon.rawValue
zPosition = 5
name = "player"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func shoot(){
let shot = SKSpriteNode(imageNamed: type.weapon)
shot.name = self.type.weapon
shot.size = CGSize(width: 50, height: 50)
shot.physicsBody = SKPhysicsBody(rectangleOf: shot.size)
shot.physicsBody?.categoryBitMask = CollisionType.playerWeapon.rawValue
shot.physicsBody?.collisionBitMask = CollisionType.enemy.rawValue | CollisionType.enemyWeapon.rawValue
shot.physicsBody?.contactTestBitMask = CollisionType.enemy.rawValue | CollisionType.enemyWeapon.rawValue
addChild(shot)
shot.zPosition = 3
shot.physicsBody?.affectedByGravity = false
let movement = SKAction.move(to: CGPoint(x: 4000, y: shot.position.y), duration: 1)
let sequence = SKAction.sequence([movement, .removeFromParent()])
shot.run(sequence)
}
func levelUp(){
self.texture = SKTexture(imageNamed: type.spriteTexture)
let texture = SKTexture(imageNamed: type.spriteTexture)
self.physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
}
}
Firstly, i'm wondering if i have this set up the right way.
In my game scene:
import SpriteKit
import GameplayKit
enum CollisionType: UInt32 {
case player = 1
case playerWeapon = 2
case enemy = 4
case enemyWeapon = 8
case ground = 16
}
class GameScene: SKScene, SKPhysicsContactDelegate {
// Properties
var isPlayerAlive = true
var playerLevels = Bundle.main.decode([PlayerLevel].self, from: "player-levels.json")
let enemyTypes = Bundle.main.decode([EnemyType].self, from: "enemies.json")
var currentEnemy = 0
var currentLevel = 0 {
didSet {
player.type = playerLevels[currentLevel]
}
}
var player: Player!
var enemy: Enemy!
var levelUp: SKSpriteNode!
var healthLabel: SKLabelNode!
var scoreLabel: SKLabelNode!
let playerLevelLabel = SKLabelNode(fontNamed: "Chalkduster")
var score = 0 {
didSet{
scoreLabel.text = "Score: \(score)"
}
}
let ground = SKSpriteNode(imageNamed: "groundBottom")
let groundT = SKSpriteNode(imageNamed: "gameGroundTop")
var expLabel: SKLabelNode!
var exp = 0 {
didSet{
expLabel.text = "Experience Points: \(exp) / \(playerLevels[currentLevel].expToLvlUp)"
}
}
var health = 0 {
didSet{
healthLabel.text = "Health: \(playerLevels[currentLevel].health)"
}
}
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
makeGround()
initializePlayer()
spawnEnemy()
makeScoreLabel()
makeExpLabel()
makeHealthLabel()
}
func initializePlayer(){
player = Player(type: playerLevels[currentLevel])
addChild(player)
playerLevelLabel.text = "Details: \(player.type)"
playerLevelLabel.fontSize = 40
playerLevelLabel.position = CGPoint(x: 0, y: self.frame.minY + 200)
}
func makeScoreLabel(){
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.position = CGPoint(x:self.frame.maxX - 250, y:self.frame.maxY - 100)
scoreLabel.horizontalAlignmentMode = .right
scoreLabel.fontSize = 40
scoreLabel.zPosition = 5
scoreLabel.text = "Score: 0"
scoreLabel.name = "score"
addChild(scoreLabel)
}
func makeExpLabel(){
expLabel = SKLabelNode(fontNamed: "Chalkduster")
expLabel.position = CGPoint(x:self.frame.minX + 500, y:self.frame.maxY - 110)
scoreLabel.fontSize = 40
expLabel.zPosition = 5
expLabel.text = "Expereience Points: 0 / \(playerLevels[currentLevel].expToLvlUp)"
expLabel.name = "exp"
addChild(expLabel)
}
func makeHealthLabel(){
healthLabel = SKLabelNode(fontNamed: "Chalkduster")
healthLabel.position = CGPoint(x:self.frame.minX + 1200, y:self.frame.maxY - 110)
healthLabel.fontSize = 40
healthLabel.zPosition = 5
healthLabel.text = "Health: \(playerLevels[currentLevel].health)"
healthLabel.name = "health"
addChild(healthLabel)
}
func makeGround(){
ground.name = "ground"
ground.position.x = frame.midX
ground.position.y = frame.minY
ground.zPosition = 1
addChild(ground)
ground.physicsBody = SKPhysicsBody(texture: ground.texture!, size: ground.texture!.size())
ground.physicsBody?.affectedByGravity = false
ground.physicsBody?.isDynamic = false
groundT.position.x = frame.midX
groundT.position.y = ground.position.y + 50
groundT.physicsBody?.isDynamic = false
addChild(groundT)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let location = touch?.location(in: self)
let nodesAtLocation = nodes(at: location!)
for node in nodesAtLocation {
if node.name == "score"{
score += 10
exp += 5
upgrade()
}
if node.name == "attack"{
attack()
}
}
}
func upgrade() {
if exp < playerLevels[currentLevel].expToLvlUp { return }
if currentLevel + 1 > playerLevels.count - 1 {
gameOver()
return
}
if let explosion = SKEmitterNode(fileNamed: "Explosion") {
explosion.position = player.position
addChild(explosion)
}
//charLevelUp()
currentLevel += 1
playerLevelLabel.text = "Details: \(player.type)"
}
func didBegin(_ contact: SKPhysicsContact) {
guard let nodeA = contact.bodyA.node else { return }
guard let nodeB = contact.bodyB.node else { return }
let sortedNodes = [nodeA, nodeB].sorted { $0.name ?? "" < $1.name ?? ""}
let firstNode = sortedNodes[0]
let secondNode = sortedNodes[1]
if firstNode.name == "ground" { return }
if secondNode.name == "ground" { return }
if secondNode.name == "player" {
guard isPlayerAlive else { return }
if let explosion = SKEmitterNode(fileNamed: "explosion"){
explosion.position = firstNode.position
addChild(explosion)
}
//health -= 1
if playerLevels[currentLevel].health == 0{
gameOver()
secondNode.removeFromParent()
}
firstNode.removeFromParent()
} else if let enemy = firstNode as? Enemy {
enemy.health -= 1
if enemy.health == 0 {
if let explosion = SKEmitterNode(fileNamed: "Explosion") {
expLabel.position = enemy.position
addChild(explosion)
}
enemy.removeFromParent()
score += 50
exp = enemy.expGive
}
if let explosion = SKEmitterNode(fileNamed: "Explosion") {
explosion.position = enemy.position
addChild(explosion)
}
secondNode.removeFromParent()
} else {
if let explosion = SKEmitterNode(fileNamed: "Explosion") {
explosion.position = secondNode.position
addChild(explosion)
}
firstNode.removeFromParent()
secondNode.removeFromParent()
}
}
I've managed to get the sprite to change texture and physics body, the expReq points to change based on the players level, however, I can't seem to update the health property or any of the others. Any help would be appreciated - I'm not sure if I have this set up correctly - please advise :)
I'm trying to parse a Json data using Alamofire in my App. I get the results and show them in tableView. However, I need to view results by their id object in Json result. For example if id=4, I just need to show which include id=4 object data in tableView.
Here's my code try to work. And Json data as well:
Json data:
{
data = (
{
content = "harika!! nerdeydiniz bu zamana kadar";
createdAt = {
date = "2019-06-04 12:34:22.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 1;
};
rating = 4;
},
{
content = "bu kadar\U0131 da olmaz";
createdAt = {
date = "2019-06-04 18:04:02.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 1;
};
rating = 5;
},
{
content = "be\U011fendim";
createdAt = {
date = "2019-06-01 18:04:02.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 2;
};
rating = 4;
},
{
content = "tekrar istiyorum";
createdAt = {
date = "2019-06-03 18:04:02.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 2;
};
rating = 5;
},
{
content = "tarot inan\U0131lmazd\U0131 kahveyi de g\U00f6nderece\U011fim";
createdAt = {
date = "2019-06-11 18:04:02.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 2;
};
rating = 5;
},
{
content = "yorum tuttu";
createdAt = {
date = "2019-06-12 18:04:02.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 3;
};
rating = 4;
},
{
content = "ahsen ne yapt\U0131n ahsen";
createdAt = {
date = "2019-06-16 18:04:02.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 3;
};
rating = 4;
},
{
content = "gece gece heyecanlad\U0131m";
createdAt = {
date = "2019-05-25 18:06:24.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 4;
};
rating = 4;
},
{
content = "mutlu hissediyor";
createdAt = {
date = "2019-05-28 18:06:24.000000";
timezone = "Europe/Istanbul";
"timezone_type" = 3;
};
fortuneTeller = {
id = 4;
};
rating = 5;
}
);
error = 0;
message = Success;
}
var message: String?
var array = [getReviewsModel]()
var homeDict = NSDictionary()
func getReviewApi (completion: #escaping (Bool, String) -> ()) {
let url = BaseUrl + getReviewsUrl
if Reachability.isConnectedToNetwork() {
getDictDataFromServer(url: url, headers: [:], completion: { (dict) in
print (dict)
if let err = dict.value(forKey: "error")
{
let message = dict.value(forKey: "message") as? String
let error = err as! Bool
if !error {
let arr = dict.value(forKey: "data") as! NSArray
for i in 0..<arr.count {
let obj = getReviewsModel()
obj.homeDict(dict: arr[i] as! [String : Any])
self.array.append(obj)
//print(obj)
}
if (self.array.count == 0)
{
completion (false, "Yorum bulunamadı.")
return
}
completion (true, "Success")
}
else
{
completion (false, message!)
}
}
else
{
completion (false, internalServerMsg)
}
})
}
else
{
completion(false,noInternetMsg)
}
}
func setDataForCell (index: Int, cell: reviewTableViewCell){
let obj = array[index]
cell.setData(obj: obj)
}
func numberOfItemsInSection () -> Int {
return array.count
}
func fortuneTellerId (index: Int) -> Int {
let obj = array[index].id
return obj ?? 0
}
And class
var content: String?
var createdAt: String?
var rating: Double?
var id: Int?
func homeDict (dict:[String:Any]){
self.content = dict["content"] as? String ?? ""
self.createdAt = (dict["createdAt"] as? NSDictionary)?.value(forKey: "date") as? String ?? ""
self.rating = dict["rating"] as? Double
self.id = (dict["fortuneTeller"] as? NSDictionary)?.value(forKey: "id") as? Int ?? 0
}
}
Here is my tableView functions:
var viewModel_1 = DefaultFormViewModel()
var jsonDict = NSDictionary()
#IBOutlet weak var reviewDetailView: UIView!
#IBOutlet weak var reviewContentView: UIView!
#IBOutlet weak var reviewTableView: UITableView!
#IBAction func viewReviewsAction(_ sender: Any) {
reviewDetailView.isHidden = false
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel_1.numberOfItemsInSection()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? reviewTableViewCell
cell?.selectionStyle = .none
viewModel_1.setDataForCell(index: indexPath.row, cell: cell!)
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
reviewTableView.dataSource = self
reviewTableView.delegate = self
reviewTableView.separatorStyle = .none
showActivityIndicator()
viewModel_1.getReviewApi { (sucess, message) in
self.hideactivityIndicator()
if (sucess)
{
self.reviewTableView.reloadData()
}
else
{
Utility().displayAlert(title: "Title", message: message, control: ["OK"])
}
}
}
I have a little problem with looping in Swift 3. I have one JSONArray and one JSONObject like below :
dataReqList [Any] :
[{
bezeich = "MORE SALT";
grpnr = 0;
nr = 1;
}, {
bezeich = "MORE SWEET";
grpnr = 0;
nr = 2;
}, {
bezeich = "MORE PEPPER";
grpnr = 0;
nr = 3;
}, {
bezeich = "MORE CHILLI";
grpnr = 0;
nr = 4;
}, {
bezeich = COLD;
grpnr = 0;
nr = 5;
}, {
bezeich = HOT;
grpnr = 0;
nr = 6;
}, {
bezeich = SMALL;
grpnr = 0;
nr = 7;
}, {
bezeich = LARGE;
grpnr = 0;
nr = 8;
}, {
bezeich = "MEDIUM COOKED";
grpnr = 0;
nr = 9;
}, {
bezeich = "WELL DONE";
grpnr = 0;
nr = 10;
}]
currArticle [Anyhashable: Any] :
Optional([AnyHashable("bezeich"): Fresh and Green Salad,
AnyHashable("special-request"): ["MORE PEPPER", "COLD", "HOT"]])
I want to know, how to print the key bezeich in array , if the JSONArray have same String with special-request in JSONObject. I've try this but its not working :
for i in 0..<dataReqList.count {
if ( ((dataReqList[i] as? [AnyHashable: Any])? ["bezeich"] as! String) == (("\(currArticle?["special-request"]!)") as String) ) {
print (dataReqList[i])
}
Any answer and suggest will help for me. Thanks in advance
EDIT :
I'm new in Swift. I have read THIS before but its still not work.
Key special-request with currArticle Dictionary having Array of String as value so you can not directly compare it with string, you can use filter for that like this.
var filterArray = [[String:Any]]()
if let dataArray = dataReqList as? [[String:Any]],
let specialRequestArray = currArticle["special-request"] as? [String] {
filterArray = dataArray.filter { specialRequestArray.contains($0["bezeich"] as? String ?? "") }
print(filterArray)
}
I am abel to get the current and hourly weather data and based on the following criteria:
viewController:
let dailyWeather = weatherForecast.weekly[0]
let hourlyWeather = weatherForecast.hourly[hour + 4]
let weeklyWeather = weatherForecast.weekly
self.hourlySummaryLabel.text = hourlyWeather.hourlySummary
self.tomorrowSummary.text = dailyWeather.summary
forecast.swift:
struct Forecast {
var currentWeather: CurrentWeather?
var weekly: [DailyWeather] = []
var hourly: [HourlyWeather] = []
init(weatherDictionary: [String: AnyObject]){
if let currentWeatherDictionary = weatherDictionary["currently"] as? [String: AnyObject] {
currentWeather = CurrentWeather(weatherDictionary: currentWeatherDictionary)
}
if let weeklyWeatherArray = weatherDictionary["daily"]?["data"] as? [[String: AnyObject]] {
for dailyWeather in weeklyWeatherArray {
let daily = DailyWeather(dailyWeatherDictionary: dailyWeather)
weekly.append(daily)
}
}
if let hourlyWeatherArray = weatherDictionary["hourly"]?["data"] as? [[String:AnyObject]] {
for hourlyWeather in hourlyWeatherArray {
let hour = HourlyWeather(dailyWeatherDictionary: hourlyWeather)
hourly.append(hour)
}
}
}
}
however, i need to get the full day summary from the following json:
units = si;
}, "hourly": {
data = (
{
{
apparentTemperature = "33.61";
cloudCover = 0;
dewPoint = "12.77";
humidity = "0.27";
icon = "clear-day";
ozone = "279.14";
precipIntensity = 0;
precipProbability = 0;
pressure = "1004.85";
summary = Clear;
temperature = "34.66";
time = 1463464800;
windBearing = 4;
windSpeed = "2.48";
}
);
icon = wind;
summary = "Breezy until this evening."; -----> Need This Summary
is there any way to do it?
I am having some troubles with some json data. I'm making a weather app and most of the information I parsed works but the weather
this is the council output for the json data as a whole this is the section im having troubles with
the full output of json
{
base = stations;
clouds = {
all = 90;
};
cod = 200;
coord = {
lat = "39.74";
lon = "-104.98";
};
dt = 1427305893;
id = 5419384;
main = {
humidity = 84;
pressure = 1022;
temp = "274.07";
"temp_max" = "275.35";
"temp_min" = "272.15";
};
name = Denver;
rain = {
1h = "0.25";
};
snow = {
1h = "0.17";
};
sys = {
country = US;
id = 532;
message = "0.07829999999999999";
sunrise = 1427288058;
sunset = 1427332632;
type = 1;
};
visibility = 4023;
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
},
{
description = snow;
icon = 13d;
id = 601;
main = Snow;
},
{
description = fog;
icon = 50d;
id = 741;
main = Fog;
},
{
description = mist;
icon = 50d;
id = 701;
main = Mist;
}
);
wind = {
deg = 20;
gust = "14.9";
speed = "12.9";
};
}
i also have it print the keys
[base, id, dt, snow, main, coord, sys, wind, weather, visibility, clouds, cod, name, rain]
I tried to save it as an array but when I set the arry[0] to a string it crashes
my code for the function
func populateLabels(weatherData: NSData){
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: &jsonError) as NSDictionary
println(json)
if let city = json["name"] as? String {
CityName.text = city
}
println(json.allKeys)
if let coord = json["coord"] as? NSDictionary {
if let longi = coord["lon"] as? Double {
long.text = String(format: "%.2f", longi)
}
if let lati = coord["lat"] as? Double {
lat.text = String(format: "%.2f", lati)
}
}
if let main = json["main"] as? NSDictionary {
if let temper = main["temp"] as? Double {
temp.text = String(format: "%.2f", temper)
}
}
If anyone knows how to get to the description that would be awesome
thanks js
I got it.. thanks for the help blacksquare, larme, chirag90
if let tasks = json["weather"] as? NSArray
{
if let task = tasks[0] as? NSDictionary
{
if let taskName = task["description"] as? NSString
{
println(taskName)
}
}
}