I need to get the JSON value from MYSQL and display it in the table view. I have done PHP part to receive data but I have error with my XCODE. My data will store temperature, humidity and digital status (on off) of sensor. I have questions below:
How to get ON/OFF JSON value and store in Bool array?
How to get JSON value and store in Float array?
if JSON value is , how can I store value as 0 in XCODE?
class DataManager {
var nodenameArray: [String] = []
var nodeidArray: [String] = []
var tempArray: [Float] = []
var humArray: [Float] = []
var pirArray: [Bool] = []
var lightArray: [Bool] = []
var relayArray: [Bool] = []
var hallArray: [Bool] = []
var smokeArray: [Bool] = []
#objc func taskdo() {
self.nodenameArray = []
self.nodeidArray = []
self.tempArray = []
self.humArray = []
self.pirArray = []
self.lightArray = []
self.relayArray = []
self.hallArray = []
self.smokeArray = []
if userlogin == true {
let request = NSMutableURLRequest(url: NSURL(string: http://talectric.com/wp-admin/a_p/iot/read_all.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(username)&password=\(password)&authen=wdwfesf9329140dsvfxkciospdkm"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error!)")
return
} else {
do {
if let respondString = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(respondString)
if let nodedata = respondString.value(forKey: "nodedata") as? NSArray {
for node in nodedata{
if let nodeDict = node as? NSDictionary {
if let nodeid = nodeDict.value(forKey: "node_id") {
self.nodeidArray.insert(nodeid as! String, at: 0)
}
if let nodeid = nodeDict.value(forKey: "node_name") {
self.nodenameArray.insert(nodeid as! String, at: 0)
}
if let nodeid = nodeDict.value(forKey: "temp") {
self.tempArray.insert(Float(nodeid as! String)!, at: 0)
}
if let nodeid = nodeDict.value(forKey: "hum") {
print(nodeid)
self.humArray.insert(Float(Int(nodeid as! String)!), at: 0)
}
}
}
}
}
print(self.nodenameArray)
print(self.nodeidArray)
print(self.tempArray)
print(self.humArray)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
}
catch let error as NSError {
print(error.debugDescription)
}
}
}
task.resume()
}
}
}
below is the respond:
{
nodedata = (
{
"hall_status" = "<null>";
hum = 111;
"light_status" = "<null>";
"node_id" = y2cfwecrw3hqznuxmfvf;
"node_name" = SVIN03;
"pir_status" = OFF;
"relay_status" = "<null>";
"smoke_status" = "<null>";
temp = 2132;
},
{
"node_name" = SVIN04;
nodeid = aj2w1aljw8nd65ax79dm;
},
{
"hall_status" = "<null>";
hum = 100;
"light_status" = "<null>";
"node_id" = mwmfl2og2l8888fjpj2d;
"node_name" = SVIN05;
"pir_status" = ON;
"relay_status" = "<null>";
"smoke_status" = "<null>";
temp = 45;
}
);
numberofnodeid = 3;
}
111
100
Could not cast value of type '__NSCFNumber' (0x10db6f878) to 'NSString' (0x10ca71568).
2018-10-11 08:11:05.352491+0700 IOT 2[1506:101847] Could not cast value of type '__NSCFNumber' (0x10db6f878) to 'NSString' (0x10ca71568).
error is in this line :
self.humArray.insert(Float(Int(nodeid as! String)!), at: 0)
First of all, you have to look at json_decode to read data from json in php
Example:
`$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // this will print 12345`
How to get ON/OFF JSON value and store in Bool array ?
basically you have to add a new value to your onOff variable, something like
$onOff=array();
$val;
$obj = json_decode($json);
if (is_null($obj->{'name_of_the_alert'})) {
$val = 0
} else {
$val = $obj->{'name_of_the_alert'};
}
array_push($onOff,$obj->{'name_of_the_alert'});
How to get JSON value and store in Float array ?
Basically same thing, I haven't use PHP in a while, but just declare the array of the value type you need.
if JSON value is , how can i store value as 0 in XCODE ?
I guess you mean if it is null, in this case you have to do this
$onOff=array();
$val;
$obj = json_decode($json);
if (is_null($obj->{'name_of_the_alert'})) {
$val = 0
} else {
$val = $obj->{'name_of_the_alert'};
}
array_push($onOff,$obj->{'name_of_the_alert'});
Take into consideration that I may have some mistakes here because I am not familiar with newer PHP versions.
Good luck
From your question, it is clear that temp and hum are Number type(Int of Double). So use NSNumber rather than NSString as:
self.humArray.insert(Float(Int(nodeid as! NSNumber)!), at: 0)
As more swifty approach, you can update your code as:
if let nodeDict = node as? [String: Any] {
if let nodeid = nodeDict["node_id"] as? String {
self.nodeidArray.insert(nodeid, at: 0)
}
if let nodename = nodeDict["node_name"] as? String {
self.nodenameArray.insert(nodename, at: 0)
}
if let temp = nodeDict["temp"] as? Int {
self.tempArray.insert(Float(temp), at: 0)
}
if let hum = nodeDict["hum"] as? Int {
self.humArray.insert(Float(hum), at: 0)
}
}
There is plenty of issues with your code:
First, avoid using NSStuff in Swift3+ when there is the equivalent.
let request = NSMutableURLRequest(url: NSURL(string: http://talectric.com/wp-admin/a_p/iot/read_all.php")! as URL)
...
let task = URLSession.shared.dataTask(with: request as URLRequest) {
=>
let request = URLRequest(url: URL(string: http://talectric.com/wp-admin/a_p/iot/read_all.php")!)
...
let task = URLSession.shared.dataTask(with: request) {
See, you avoid already all the as URL, as URLRequest.
Avoid force unwrapping: Avoid using !.
Because if it's nil or with as! the cast fails (and then it's nil), you'll get a crash.
Use if let, guard let. Read this about Optional
As a sample, I would have wrote:
guard let url = URL(string:http...) else {
print("invalid URL")
return
}
let request = URLRequest(url: url)
Parsing part:
if let respondString = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
Get rid of NSDictionary, use [String: Any] instead, then get rid of .allowFragments, it's rarely useful (it makes sense on certains cases only) don't use the force unwrap on data!, and don't name your variable respondString
because that's clearly not a String and that's clearly misleading.
=>
guard let data = data else { return }
if let responseDict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
Now:
if let nodedata = respondString.value(forKey: "nodedata") as? NSArray {
for node in nodedata{
if let nodeDict = node as? NSDictionary {
if let nodeid = nodeDict.value(forKey: "node_id") {
self.nodeidArray.insert(nodeid as! String, at: 0)
}
if let nodeid = nodeDict.value(forKey: "node_name") {
self.nodenameArray.insert(nodeid as! String, at: 0)
}
if let nodeid = nodeDict.value(forKey: "temp") {
self.tempArray.insert(Float(nodeid as! String)!, at: 0)
}
if let nodeid = nodeDict.value(forKey: "hum") {
print(nodeid)
self.humArray.insert(Float(Int(nodeid as! String)!), at: 0)
}
}
}
}
No, no NSArray, no NSDictionary, avoid using value(forKey:) because it does what you think it does on a NSDictionary doing a object(forKey:), or simply subscript (using ["someKey"]) but on an Array you'll get an issue with an unexpected result I think.
Don't name all your var nodeid, it's harder to debug after ward, don't do a soft unwrap (if let) if just afterward you do a force unwrap on that value.
if let nodedata = responseDict["nodedata"] as? [[String: Any]] {
for aNode in nodedata {
if let id = aNode["node_id"] as? String {
self.nodeidArray.insert(nodeId, at: 0)
}
if let name = aNode["node_name"] as? String {
self.nodenameArray.insert(name, at: 0)
}
if let temp = aNode["temp"] as? String, let tempFloat = Float(temp) {
self.tempArray.insert(tempFloat, at: 0)
}
if let hum = aNode["hum"] as? String, let humFloat = Float(hum) {
self.humArray.insert(humFloat, at: 0)
}
}
}
That's much more readable.
Now instead of using insert(_:at:), it might be easier to use nodedata.inverted().
Now, let's talk about architecture:
What happens in your case, if you don't pass the if let hum = aNode["hum"] as? String, let humFloat = Float(hum) { on one iteration (let's say the second one which is exactly your case in the sample you gave there is no temp) but success on all the others?
Here what's going to happen:
self.nodeidArray[3] and self.humArray[3] won't be correct, they'll be desynchronized, right?
Because self.nodeidArray[2] should be with self.humArray[1].
Theses values are meant to be synce'd, so use a custom Struct/Class for it:
After all, Swift is a OOP (Object Oriented Programming) language, so use objects.
struct Node {
let id: String?
let name: String?
let humidity: Float?
let temperature: Float?
}
So instead of having:
var nodenameArray: [String] = []
var nodeidArray: [String] = []
var tempArray: [Float] = []
var humArray: [Float] = []
Just have:
var nodes: [Node] = []
And during the parsing, do
let node = Node.init(withDict: aNode)
nodes.append(node) //or insert it at 0
You can construct your own method init in Node, let's say:
func init(withDict dict: [String: Any]) {
if let id = dict["node_id"] as? String {
self.id = id
}
etc.
}
Having this Node class simplify. But using the JSONSerialization and init all the values manually could be avoided using Codable (available in Swift 4).
Side Note:
This code is not tested, there might be some glitch, typo etc. Let's focus on the explanation instead.
Lastly concerning the error:
Could not cast value of type '__NSCFNumber' (0x10db6f878) to
'NSString' (0x10ca71568). 2018-10-11 08:11:05.352491+0700 IOT
2[1506:101847] Could not cast value of type '__NSCFNumber'
(0x10db6f878) to 'NSString' (0x10ca71568).
error is in this line :
self.humArray.insert(Float(Int(nodeid as! String)!), at: 0)
The error means that at some point you tried to cas (using as) on a a (NS)String, but is was in fact NSNumber (in Swift, it's easily converted into an Int/Float, etc.), so it failed.
So the part that failed: nodeid as! String, because nodeid is not a (NS)String
Related
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?
And Hier is my code:
func apiRequest() {
let config = URLSessionConfiguration.default
let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
let password = "G23#rE9t1#"
let loginString = String(format: "%#:%#", username, password)
let userPasswordData = loginString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData?.base64EncodedString()
let authString = "Basic " + (base64EncodedCredential)!
print(authString)
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)
var running = false
let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")
let task = session.dataTask(with: url! as URL) {
( data, response, error) in
if let taskHeader = response as? HTTPURLResponse {
print(taskHeader.statusCode)
}
if error != nil {
print("There is an error!!!")
print(error)
} else {
if let content = data {
do {
let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(array)
if let items = array["items"] {
if let description = items["Description"] as? [[String:Any]]{
print(description as Any)
}
}
}
catch {
print("Error: Could not get any data")
}
}
}
running = false
}
running = true
task.resume()
while running {
print("waiting...")
sleep(1)
}
}
First of all the array is not an array and not AnyObject, it's a dictionary which is [String:Any] in Swift 3.
let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)
I don't know why all tutorials suggest .mutableContainers as option. That might be useful in Objective-C but is completely meaningless in Swift. Omit the parameter.
The object for key itemsis an array of dictionaries (again, the unspecified JSON type in Swift 3 is Any). Use a repeat loop to get all description values and you have to downcast all values of a dictionary from Any to the expected type.
if let items = dictionary["items"] as? [[String:Any]] {
for item in items {
if let description = item["Description"] as? String {
print(description)
}
}
}
Looks like items is an array that needs to be looped through. Here is some sample code, but I want to warn you that this code is not tested for your data.
if let items = array["items"] as? [[String: AnyObject]] {
for item in items {
if let description = item["Description"] as? String{
print("Description: \(description)")
}
}
}
This code above, or some variation of it, should get you on the right track.
use the SwiftyJSON and it would be as easy as json["items"][i].arrayValue as return and array with items Values or json["items"][i]["description"].stringValue to get a string from a row
I am trying to access items parsed in JSON from the iTunes API using Swift 3.0, but I am struggling to access the objects after they have been parsed. The objects are being parsed in this format:
{
resultCount = 50;
results = (
{
artistId = 70936;
artistName = "Johnny Cash";
artistViewUrl = "https://itunes.apple.com/us/artist/johnny-cash/id70936?uo=4";
artworkUrl100 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/100x100bb.jpg";
artworkUrl30 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/30x30bb.jpg";
artworkUrl60 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/60x60bb.jpg";
collectionCensoredName = "The Essential Johnny Cash";
collectionExplicitness = notExplicit;
collectionId = 251001680;
collectionName = "The Essential Johnny Cash";
collectionPrice = "14.99";
collectionViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
country = USA;
currency = USD;
discCount = 2;
discNumber = 1;
isStreamable = 1;
kind = song;
previewUrl = "http://a1144.phobos.apple.com/us/r1000/070/Music/b3/99/be/mzi.qvkhtgfg.aac.p.m4a";
primaryGenreName = Country;
releaseDate = "2002-02-12T08:00:00Z";
trackCensoredName = "Ring of Fire";
trackCount = 18;
trackExplicitness = notExplicit;
trackId = 251002253;
trackName = "Ring of Fire";
trackNumber = 15;
trackPrice = "1.29";
trackTimeMillis = 155707;
trackViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
wrapperType = track;
},
I want to be able to access the information from all 50 results, such as the artistName, for instance. This is my parsing function attempting to get the artistName and add it to my NSDictionary, but it keeps returning that it can't unwrap the dictionary.
func parser() {
let enteredText:String = (tbxSearch.text?.replacingOccurrences(of: " ", with: "+"))!
let url = "https://itunes.apple.com/search?term=\(enteredText)"
print(url)
guard let urlRequest = URL(string: url) else
{
print("Error creating endpoint")
return
}
let request = URLRequest(url: urlRequest)
URLSession.shared.dataTask(with: request) {(data,response,error) in
do
{
guard let data = data else
{
return
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else
{
return
}
if let results = json["results"] as? NSDictionary
{
self.avObjects.avDict.setValue("Artist Name", forKey: results["artistName"] as! String)
print(self.avObjects.avDict)
}
else
{
print("Couldn't unwrap the dictionary.")
}
print(json)
}
catch let error as NSError
{
print(error.debugDescription)
}
}.resume()
}
It looks like results is an array of dictionaries, not just a dictionary.
Instead of this: if let results = json["results"] as? NSDictionary
try this: if let results = json["results"] as? NSArray
You could then map or iterate over each element in the array, extracting "artistName" from each one, for example.
results is an array of dictionaries, not a dictionary itself. Try changing this:
if let results = json["results"] as? NSDictionary
to:
if let results = json["results"] as? NSArray
and then iterating over results. Each element of results is a dictionary with attributes such as artistName.
I am trying to parse some json data into three different arrays based off the label in the json. I seem to be stuck and don't know why my for loop is never being entered. I am new to iOS and am using this to learn swift. Any help will be appreciated.
Here is the code that I am using:
var myPicture = [String]()
var myPath = [String]()
var mylabel = [String]()
let jsonString = "[{\"picture\" : \"Picture 1 \", \"path\": \"Path 1\" , \"label\" : \"Label 1\"}]"
//Convert jsonString to NSData
let myData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do{
let promoJson = try NSJSONSerialization.JSONObjectWithData(myData, options:.AllowFragments)
if let promtions = promoJson[""] as? [[String: AnyObject]] {
for promtions in promtions {
if let picture = promtions["picture"] as? String
{
myPicture.append(picture)
if let path = promtions["path"] as? String
{
myPath.append(path)
if let label = promtions["label"] as? String
{
mylabel.append(label)
}
}
}
}
}
}catch {
print("Error with Json: \(error)")
}
print(myPicture.first)
print(myPath.first)
print(mylabel.first)
The results for the print are all nil. So nothing is being appended to the arrays
The if let promtions = promoJson[""] part won't work and would be useless anyway. This is only promoJson that you have to cast to an array of dictionaries.
You weren't that far from the solution, look at my working version of your code:
do {
let promoJson = try NSJSONSerialization.JSONObjectWithData(myData, options: [])
if let promtions = promoJson as? [[String: AnyObject]] {
for promtion in promtions {
if let picture = promtion["picture"] as? String {
myPicture.append(picture)
}
if let path = promtion["path"] as? String {
myPath.append(path)
}
if let label = promtion["label"] as? String {
mylabel.append(label)
}
}
}
} catch let error as NSError {
print(error.debugDescription)
}
Alternative
Now that the issue is resolved, let me suggest you another way: instead of separate arrays for your data, use one array of objects holding your data.
For example, make a struct like this:
struct Promotion {
let picture: String
let path: String
let label: String
}
And an array for instances of this struct:
var myPromotions = [Promotion]()
Now we can decode the JSON, create objects from it then store them in the array:
do {
let promoJson = try NSJSONSerialization.JSONObjectWithData(myData, options: [])
if let promtions = promoJson as? [[String: AnyObject]] {
for promtion in promtions {
if let picture = promtion["picture"] as? String,
path = promtion["path"] as? String,
label = promtion["label"] as? String {
let promo = Promotion(picture: picture, path: path, label: label)
myPromotions.append(promo)
}
}
}
} catch let error as NSError {
print(error.debugDescription)
}
Now look at the content of the array, very convenient:
for promo in myPromotions {
print(promo.label)
print(promo.path)
print(promo.picture)
}
When you are converting it is already an array.
import Foundation
import UIKit
var myPicture = [String]()
var myPath = [String]()
var mylabel = [String]()
let jsonString = "[{\"picture\" : \"Picture 1 \", \"path\": \"Path 1\" , \"label\" : \"Label 1\"}]"
//Convert jsonString to NSData
let myData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do{
let promoJson = try NSJSONSerialization.JSONObjectWithData(myData, options:.AllowFragments) as! NSArray
for promtions in promoJson {
if let picture = promtions["picture"] as? String
{
myPicture.append(picture)
if let path = promtions["path"] as? String
{
myPath.append(path)
if let label = promtions["label"] as? String
{
mylabel.append(label)
}
}
}
}
}catch
{
print("Error with Json: \(error)")
}
print(myPicture.first) // "Optional("Picture 1 ")\n"
print(myPath.first) // "Optional("Path 1")\n"
print(mylabel.first) // "Optional("Label 1")\n"
This does the job.
There is a method used to fill realm database from json:
func parseJSON(data: NSData) -> NSArray? {
do {
let array: NSArray = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as! NSArray
return array
} catch _ {
return nil
}
}
//parameter came from previous method
func updateDatabaseFromParsedJson(parsedJson: NSArray) {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
for i in 0..<parsedJson.count {
let deviceObject = parsedJson[i]
let name = deviceObject["name"] as! String
let id = deviceObject["id"] as! Int
var device = Device()
device.name = name
device.id = id
try! realm.write {
realm.add(device)
}
var deviceMeasuresArray = deviceObject["measures"] as! NSArray
for i in 0..<deviceMeasuresArray.count {
var measureObject = deviceMeasuresArray[i]
var measure = Measure()
measure.slug = measureObject["name"]
measure.device = device
measure.localize()
try! realm.write {
realm.add(measure)
}
var measureEntriesArray = measureObject["averages"] as! NSArray
for i in 0..<measureEntriesArray.count {
var entryObject = measureEntriesArray[i]
var entry = PeriodAverage()
entry.measure = measure
entry.value = entryObject["value"]
entry.start = NSDate.parse(entryObject["start"])
entry.end = NSDate.parse(entryObject["end"])
entry.length = entryObject["length"]
try! realm.write {
realm.add(entry)
}
}
}
}
}
extension NSDate {
class func parse(dateString: String) -> NSDate {
let format = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.dateFromString(dateString)!
}
}
JSON itself http://188.166.51.200/api/v1/actual_data/
While compiling I get error Error:unable to execute command: Segmentation fault: 11
Where I am wrong and how to properly parse my json? I think problem is in lines where json fields forcely parsed to objects but I am new in swift and can't exactly determine the error.
You've apparently run across a compiler issue (which you should report to Apple), although it's easy enough to work around. If you're using Swift you should really be using Swift collection types instead Foundation collection types if possible (i.e., Array instead of NSArray) which allow for more type information. Also, while you're casting some of the values you're getting out of your JSON, you're not casting them all. Adding this additional type information will make the compiler behave and work around the issue. I would suggest the following edit:
func updateDatabaseFromParsedJson(parsedJson: Array<AnyObject>) {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
for i in 0..<parsedJson.count {
let deviceObject = parsedJson[i] as! Dictionary<String, AnyObject>
let name = deviceObject["name"] as! String
let id = deviceObject["id"] as! Int
var device = Device()
device.name = name
device.id = id
try! realm.write {
realm.add(device)
}
var deviceMeasuresArray = deviceObject["measures"] as! Array<AnyObject>
for i in 0..<deviceMeasuresArray.count {
var measureObject = deviceMeasuresArray[i] as! Dictionary<String, AnyObject>
var measure = Measure()
measure.slug = measureObject["name"] as! String // I'm guessing on the type here
measure.device = device
measure.localize()
try! realm.write {
realm.add(measure)
}
var measureEntriesArray = measureObject["averages"] as! Array<AnyObject>
for i in 0..<measureEntriesArray.count {
var entryObject = measureEntriesArray[i] as! Dictionary<String, AnyObject>
var entry = PeriodAverage()
entry.measure = measure
entry.value = entryObject["value"] as! String // Guessing on the type here also
entry.start = NSDate.parse(entryObject["start"] as! String)
entry.end = NSDate.parse(entryObject["end"] as! String)
entry.length = entryObject["length"] as! String // Again, guessing on the type here
try! realm.write {
realm.add(entry)
}
}
}
}
}
Unrelated to the compiler issue, you could also use for-in loops to make your code more Swift like. You can read more about them in the For-In Loops section of the Control Flow chapter of The Swift Programming Language.
I have the following code that populates a UITableView. The end var holds the number of items in the JSON response. I concatenate variable n with the counter i. My problem is that in this case the JSON response carries only two items, Request1 and Request2. When the counter reaches 3 the app crashes because there is no Request3. How can I change my loop to stop when the condition counter > end is met?
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
for item in jsonData! {
i++
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}
Try the following:
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
for item in jsonData! {
i++
// This should do it
if i == end {
break;
}
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}
I'm assuming that by counter > end you mean i > end, as it's what seems to make sense to me.
Try starting your counter i with 1 rather than 0 incrementing it at the end of the loop like this:
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
for item in jsonData! {
i++;
if(i==end)break;
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}
Also you can consider the following way of doing it
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
while(i<end) { //since we are iterating on the basis on the number and specific hardcoded keys of jsondata (and not item) we can just use a normal while loop
i++;
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}