How can I view this Json in tableView by id's - json

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"])
}
}
}

Related

Using JSON with sprite kit to set up a player who can level up

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 :)

Array in Array Swift 4 Json

["?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)
})

Array of dictionaries to JSON in Swift

I'm trying to send an array of dictionaries as one of the parameters to an Alamofire request. However, Alamofire is failing on the request.
class PromoCategory {
var promoCategoryId : Int?
var activityId : Int?
var promoCategoryName : String?
var activityName : String!
var statusCd : Int?
init() {
promoCategoryId = 0
promoCategoryName = ""
}
func getDictFormat() -> [String: Any] {
if activityId == nil { activityId = 0 }
if statusCd == nil { statusCd = 0 }
return [
"promoCategoryId" : "\(promoCategoryId!)",
"activityId" : "\(activityId!)",
"promoCategoryName" : promoCategoryName!,
"activityName" : activityName!,
"statusCd" : "\(statusCd!)"
]
}
}
var promoCat = [[String: Any]]()
for cat in promoCategories {
let element = cat.getDictFormat()
promoCat.append(element)
}
var params : [String : Any] = [:]
params["person_id"] = kPersonId
params["person_promo_id"] = promo.personPromoId
params["promo_page_id"] = promo.promoPageId
params["seq_no"] = promo.seqNo
params["promo_type"] = promoTypeString
params["page_name"] = promo.pageName
params["image_name"] = promo.imageName
params["start_date"] = promo.startDate
params["end_date"] = promo.endDate
params["website"] = promo.website
...
params["promoCategories"] = promoCat
Alamofire.request(promoUrl!, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.validate()
.responseJSON { response in
switch response.result {
case .success(let data):
self.json = JSON(data)
print(self.json as Any)
DispatchQueue.main.async(execute: { () -> Void in
self.dismiss(animated: true, completion: nil)
HUD.hide()
})
case .failure(let error):
self.logApiError(url: (...)
}
}
The error:
Request failed with error:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
If I remove the promoCategories parameter, then it works fine. The params object ends up looking like this:
{
address = "";
bgColorBlue = "0.28936631944444";
bgColorGreen = "0.3072916666666701";
bgColorRed = "0.3063227289789799";
city = "";
"contact_name" = "John Smith";
"contact_phone" = 3065554611;
"country_cd" = CA;
"end_date" = "2017-01-26 21:06:08Z";
"facility_name" = "Conexus Arts Centre";
"image_name" = "EV1.20170126210608302479028.jpg";
latitude = 0;
longitude = 0;
"page_name" = "Test Promo";
"person_id" = 1;
"person_promo_id" = 21;
promoCategories = (
{
activityId = 68;
activityName = "Fashion & Beauty";
promoCategoryId = 271;
promoCategoryName = Accessories;
statusCd = 0;
},
{
activityId = 68;
activityName = "Fashion & Beauty";
promoCategoryId = 273;
promoCategoryName = Beauty;
statusCd = 0;
},
{
activityId = 68;
activityName = "Fashion & Beauty";
promoCategoryId = 270;
promoCategoryName = Fashion;
statusCd = 0;
}
);
"promo_page_id" = 0;
"promo_type" = event;
"prov_state_cd" = "";
"seq_no" = 0;
"start_date" = "2017-01-26 21:06:08Z";
website = "";
}
Is this the approach I should be using? Is there something I have missed? Thanks.

JSON data keep on returning nil

So I have successfully declared some variables obtained by JsonDictionary, but keep on getting nil, here's my code when declaring the variables:
var userName : String!
var text : String!
var name : String!
var tweetID : [NSObject : String]!
var tweetIDStr : String!
var userLocation : String!
var UserImgURLStr : String?
var options : NSJSONReadingOptions!
init(jsonDataDictiony : [String : AnyObject])
{
self.text = jsonDataDictiony["text"] as! String
self.tweetIDStr = jsonDataDictiony["id_str"] as! String
//print(jsonDataDictiony)
if let userDictionary = jsonDataDictiony["user"] as? [String : AnyObject]
{
self.userName = userDictionary["screen_name"] as! String
self.userLocation = userDictionary["location"] as! String
self.name = userDictionary["name"] as! String
}
print(self.text)
print(self.userName)
print(self.userLocation)
print(self.tweetIDStr)
print("-")
}
func castStringToDictionary()
{
let jsonData : NSData = tweetIDStr.dataUsingEncoding(NSUTF8StringEncoding)!
self.tweetID = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: options) as! [NSObject : String]
}
and this is the code when trying to call the function (different class):
var selectedTweet : Tweet!
var twitterNetworkController : NetworkController!
var theTweet = [Tweet]()
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationItem.title = selectedTweet.name + "'s tweet"
twitterNetworkController.fetchTweetID(selectedTweet.tweetID!)
//it gets a nil value here ^
{
(results, error) in
if error == nil
{
self.theTweet = results!
self.selectedFeedTableView.reloadData()
}
else
{
print(error)
}
}
}
Here's the console print:
["in_reply_to_user_id": , "possibly_sensitive_appealable": 0, "favorite_count": 0, "possibly_sensitive": 0, "in_reply_to_status_id": , "in_reply_to_user_id_str": , "lang": en, "favorited": 0, "id": 736420019152637952, "text": 🐐 (at Sate Tegal Marem) — url, "coordinates": , "geo": , "user": {
"contributors_enabled" = 0;
"created_at" = "Mon May 21 09:06:46 +0000 2012";
"default_profile" = 0;
"default_profile_image" = 0;
description = "\Uad1c\Ucc2e\Uc744\Ud150\Ub370 \U2b50";
entities = {
description = {
urls = (
);
};
};
"favourites_count" = 11;
"follow_request_sent" = 0;
"followers_count" = 155;
following = 1;
"friends_count" = 134;
"geo_enabled" = 0;
"has_extended_profile" = 0;
id = 586390966;
"id_str" = 586390966;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 0;
location = "";
name = "tania.";
notifications = 0;
"profile_background_color" = B4DEBA;
"profile_background_image_url" = img url;
"profile_background_image_url_https" = img url;
"profile_background_tile" = 0;
"profile_banner_url" = banner url = img url;
"profile_image_url_https" = img url;
"profile_link_color" = 44A681;
"profile_sidebar_border_color" = FFFFFF;
"profile_sidebar_fill_color" = FFFFFF;
"profile_text_color" = 333333;
"profile_use_background_image" = 1;
protected = 0;
"screen_name" = "tania_alice";
"statuses_count" = 2332;
"time_zone" = Jakarta;
url = "";
"utc_offset" = 25200;
verified = 0;
}, "id_str": 736420019152637952, "created_at": Sat May 28 04:53:09 +0000 2016,
I replaced all the urls since it gave error (my reputation is less than 10 and I cannot post urls)

Day Summary from JSON and swift

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?