Append data to multidimensional array (swift) - ios

I'm having a problem with passing data in an multidimensional array.
So this is the Array:
var dataHome:[[String]] = []
And I would like to pass data into it like this:
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
if let country_obj = countries_list[i] as? NSDictionary
{
println(country_obj)
let countryName = country_obj["country"] as! String
let countryCode = country_obj["code"] as! String
var tempArray:[String] = []
tempArray.append(countryName)
tempArray.append(countryCode)
println(tempArray)
dataHome.append(tempArray)
println(dataHome)
}
}
}
It crashes when I try to pass data into dataHome.append(tempArray)
The array from country_obj is {code = US;country = Amerika;}
Does anybody have an solution ?
Thank's !
EDIT:
the whole function is:
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
if (parseError == nil)
{
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
if let country_obj = countries_list[i] as? NSDictionary
{
println(country_obj)
var countryName = country_obj["country"] as! String
var countryCode = country_obj["code"] as! String
println(countryName)
println(countryCode)
var tempArray:[String] = []
tempArray.append(countryName)
tempArray.append(countryCode)
println(tempArray)
dataHome.append(tempArray)
println(dataHome)
}
}
}
}
do_table_refresh();
}
The error is: Thread 3: Breakpoint 2.1
tempArray.append(countryName)

Related

How to get the attribute from model class and pass to collection view in swift 3

Here I am having collection view in which data will be passing from model class here I need to get special_price key value pair from CustomAttribute and need to pass for collection view in which only some products will have special price and some products won't have special price how to pass the data to collection view I am unable to implement it can anyone help me how to pass data new to swift 3 if anything wrong in declaring or writing model class please correct me ?
var listClassModel : ModelClass?
var items = [List]()
func listCategoryDownloadJsonWithURL(listUrl: String) {
print(listUrl)
let url = URL(string: listUrl)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil { print(error!); return }
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:AnyObject] {
let objArr = jsonObj["items"] as? [[String:Any]]
let objAdd = objArr!.map{List(dict: $0)}
self.items.append(contentsOf: objAdd)
self.listClassModel = ModelClass(dict: jsonObj as [String : AnyObject])
DispatchQueue.main.async {
guard let obj = self.listClassModel else { return }
let itemsCount = obj.items.count
print(itemsCount)
for i in 0..<itemsCount {
let customAttribute = obj.items[i].customAttribute
print(customAttribute.count)
for j in 0..<customAttribute.count {
if customAttribute[j].attributeCode == "image" {
let baseUrl = "http://192.168.1.11/magento2/pub/media/catalog/product"
self.listCategoryImageArray.append(baseUrl + customAttribute[j].value)
}
if customAttribute[j].attributeCode == "special_price" {
self.specialPrice.append(customAttribute[j].value)
}
}
}
print(self.specialPrice)
self.activityIndicator.stopAnimating()
self.activityIndicator.hidesWhenStopped = true
self.collectionView.reloadData()
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.isHidden = false
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
task.resume()
}
Here is my model class
struct ModelClass {
var items : [List]
var totalCount : Int
var searchCriteria : SearchCriteria
init(dict:[String:AnyObject]) {
totalCount = dict["total_count"] as! Int
let searchDict = dict["search_criteria"] as? [String:AnyObject]
searchCriteria = SearchCriteria(dict: searchDict!)
let arr = dict["items"] as? [[String:AnyObject]]
var listArr = [List]()
for obj in arr! {
listArr.append(List(dict: obj))
}
items = listArr
}
}
struct List {
let name : String
let sku : Any
let id : Int
let attributeSetId : Int
let price : Int
let status : Int
let visibility : Int
let typeId: String
let createdAt : Any
let updatedAt : Any
var customAttribute = [ListAttribute]()
init(dict : [String:Any]) {
if let customAttribute = dict["custom_attributes"] as? [[String: AnyObject]] {
var result = [ListAttribute]()
for obj in customAttribute {
result.append(ListAttribute(json: obj)!)
}
self.customAttribute = result
} else {
self.customAttribute = [ListAttribute]()
}
self.name = (dict["name"] as? String)!
self.sku = dict["sku"]!
self.id = (dict["id"] as? Int)!
self.attributeSetId = (dict["attribute_set_id"] as? Int)!
self.price = (dict["price"] as? Int)!
self.status = (dict["status"] as? Int)!
self.visibility = (dict["visibility"] as? Int)!
self.typeId = (dict["type_id"] as? String)!
self.createdAt = dict["created_at"]!
self.updatedAt = dict["updated_at"]!
}
}
struct ListAttribute {
let attributeCode : String
let value : String
init?(json : [String:AnyObject]) {
self.attributeCode = (json["attribute_code"])! as! String
self.value = (json["value"])! as! String
}
}
Here is my image how my Json looks

I am unable to get the child names from given url in swift 3?

In the api am getting global array but in this I am unable to get the children names as separate array only the last loaded array name has been getting in the array how to get the all children names in the array please help me how to get all the names in it and here is my code already tried
var detailsArray = NSArray()
var globalArray = NSMutableArray()
let url = "http://www.json-generator.com/api/json/get/cwqUAMjKGa?indent=2"
func downloadJsonWithURL() {
let url = NSURL(string: self.url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
self.detailsArray = (jsonObj?.value(forKey: "data") as? [[String: AnyObject]])! as NSArray
print(self.detailsArray)
for item in self.detailsArray
{
let majorDic = NSMutableDictionary()
let detailDict = item as! NSDictionary
print(detailDict["name"]!)
majorDic .setValue(detailDict["name"]!, forKey: "name")
print(detailDict["children"]!)
if !(detailDict["children"]! is NSNull)
{
let children = detailDict["children"]! as! NSArray
let childrenstring = NSMutableString()
if children.count > 0 {
for item in children{
let chilDic = item as! NSDictionary
print(chilDic["name"]!)
print(chilDic["products"]!)
majorDic.setValue(chilDic["name"]!, forKey: "Childernname")
let products = chilDic["products"]! as! NSArray
if products.count > 0
{
for item in products
{
var sr = String()
sr = (item as AnyObject) .value(forKey: "name") as! String
childrenstring.append(sr)
childrenstring.append("*")
}
majorDic.setValue(childrenstring, forKey: "Childernproducts")
}
else
{
print("products.count\(products.count)")
majorDic.setValue("NO DATA", forKey: "Childernproducts")
}
}
}
else
{
print("childernw.count\(children.count)")
majorDic.setValue("NO DATA", forKey: "Childernname")
}
}
else
{
majorDic.setValue("NO DATA", forKey: "Childernname")
majorDic.setValue("NO DATA", forKey: "Childernproducts")
}
self.globalArray.add(majorDic)
}
print("TOTAL ASSECTS\(self.globalArray)")
OperationQueue.main.addOperation({
self.tableView.reloadData()
print(self.globalArray)
print(self.detailsArray)
})
}
}).resume()
}
Try this:
var detailsArray = [DataList]()
func downloadJsonWithURL() {
let url = NSURL(string: "http://www.json-generator.com/api/json/get/cwqUAMjKGa?indent=2")
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
let objArr = (jsonObj?["data"] as? [[String: AnyObject]])! as NSArray
for obj in objArr {
self.detailsArray.append(DataList(json: obj as! [String : AnyObject]))
}
print(self.detailsArray)
}
}).resume()
}
Model Class
class DataList: NSObject {
var count: Int
var category_id: Int
var childern:[Children]
var name:String
init (json: [String: AnyObject]){
if let childrenList = json["children"] as? [[String: AnyObject]] {
var result = [Children]()
for obj in childrenList {
result.append(Children(json: obj))
}
self.childern = result
} else {
self.childern = [Children]()
}
if let count = json["count"] as? Int { self.count = count }
else { self.count = 0 }
if let category_id = json["category_id"] as? Int { self.category_id = category_id }
else { self.category_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
class Children:NSObject{
var count:Int
var category_id:Int
var products:[Products]
var name:String
init (json: [String: AnyObject]){
if let productList = json["products"] as? [[String: AnyObject]] {
var result = [Products]()
for obj in productList {
result.append(Products(json: obj))
}
self.products = result
} else {
self.products = [Products]()
}
if let count = json["count"] as? Int { self.count = count }
else { self.count = 0 }
if let category_id = json["category_id"] as? Int { self.category_id = category_id }
else { self.category_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
class Products:NSObject{
var product_id:Int
var name:String
init (json: [String: AnyObject]){
if let product_id = json["product_id"] as? Int { self.product_id = product_id }
else { self.product_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
NOTE: Please check your data type while parsing
I too had the same problem. Instead of using for loop try using flatMap() and then extract the value using value(forKey: " ") function
let productNames = productValues.flatMap() {$0.value}
let names = (productNames as AnyObject).value(forKey: "name")
It had worked for me for my json. My Json was similar to yours.
I got separate values in array.

Trouble with JSON parsing in swift 1.2

Trouble with JSON parsing in swift 1.2
I have an issue with the JSON parsing, i am not getting the correct data response for my parameters. i have been stuck on the issue for quite some time now. i don’t know how to fix it. i am new to iOS development. also i haven’t used any third party library.[Don’t know how to use them]
I am getting the right response for my very first iteration but for the next iteration results of previous iteration is added along with the new results. Like that each loop result is ended up with the results of previous iteration
My JSON SAMPLE.[can provide link, please let me know]
struct AssetItems {
var Name:String
var Desc:String
var Image:String
var entityId:String
var aFileType:String
var aFileSize:String
var aFileCreatedDate:String
var aFileRevisionDate:String
var aFileModifiedDate:String
var aProductName:String
var aVersion:String
var aAssetType:String
var aIsFolder:String
init(assetName:String,assetDescription:String,assetImage:String,entityId:String,FileType:String,FileSize:String,FileCretedDate:String,FileReveisionDate:String,FileModifiedDate:String,ProductName:String,Version:String,AssetType:String,IsFolder:String) {
self.Name = assetName
self.Desc = assetDescription
self.Image = assetImage
self.entityId = entityId
self.aFileType = FileType
self.aFileSize = FileSize
self.aFileCreatedDate = FileCretedDate
self.aFileRevisionDate = FileReveisionDate
self.aFileModifiedDate = FileModifiedDate
self.aProductName = ProductName
self.aVersion = Version
self.aAssetType = AssetType
self.aIsFolder = IsFolder
}
}
struct AssetModel {
var aName:String
var aDesc:String
var aCount:String
var aEntityId:String
var items:[AssetItems]
init(rackName:String,rackDescription:String,totalNoAssets:String,EntityId:String,rackItems:[AssetItems]) {
self.aName = rackName
self.aDesc = rackDescription
self.aCount = totalNoAssets
self.aEntityId = EntityId
self.items = rackItems
}
}
var assetData:Array<AssetModel> = Array<AssetModel>()
var assetContents:Array<AssetItems> = Array<AssetItems>()
THIS IS HOW I AM PARSING JSON
func get_data_from_Url(url:String) {
let url = NSURL(string: url)
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content_Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var responseError : NSError?
var response : NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
if(urlData != nil) {
var responseData:NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)!
let res = response as! NSHTTPURLResponse
var err:NSError?
if (res.statusCode == 200)
{
var parseError: NSError?
let json:AnyObject = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &err) as AnyObject!
if (parseError == nil) // no error while parsing
{
if let Asset_list = json as? NSArray
{
for (var i = 0; i < Asset_list.count ; i++ )
{
if let Asset_obj = Asset_list[i] as? NSDictionary
{
if let AssetGroupName = Asset_obj["Name"] as? String
{
if let AssetGroupDescription = Asset_obj["Description"] as? String
{
if let entityId = Asset_obj["EntityId"] as? String
{
if let totalAssets = Asset_obj["_NoOfAssets"] as? String
{
if let items = Asset_obj["Items"] as? NSArray
{
for (var j=0 ; j < items.count; j++)
{
if let asset_items = items[j] as? NSDictionary
{
if let AbsolutePath = asset_items["AbsolutePath"] as? String
{
if let Description = asset_items["_Description"] as? String
{
if let Name = asset_items["_Name"] as? String {
if let entityId = asset_items["EntityId"] as? String
{
if let FileType = asset_items["_FileType"] as? String
{
if let FileSize = asset_items["_FileSize"] as? String
{
if let FileCreatedDate = asset_items["CreatedDate"] as? String
{
if let FileModifiedDate = asset_items["ModifiedDate"] as? String
{
if let RevisionDate = asset_items["RevisionDate"] as? String
{
if let productName = asset_items["ProductName"] as? String
{
if let version = asset_items["Version"] as? String
{
if let AssetType = asset_items["_AssetType"] as? String
{
if let isFolder = asset_items["IsFolder"] as? String
{
var add = AssetItems(assetName: Name, assetDescription: Description, assetImage: AbsolutePath, entityId: entityId, FileType: FileType, FileSize: FileSize, FileCretedDate: FileCreatedDate, FileReveisionDate: RevisionDate, FileModifiedDate: FileModifiedDate, ProductName: productName, Version: version, AssetType: AssetType, IsFolder: isFolder)
assetContents.append(add)
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
var add_it = AssetModel(rackName: AssetGroupName, rackDescription: AssetGroupDescription, totalNoAssets: totalAssets, EntityId: entityId, rackItems: assetContents)
assetData.append(add_it)
}
}
}
}
}
}
}
}
}
}
}
do_table_refresh()
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(),
{
self.tableView.reloadData()
})
return
}
My Output
Please some one help me fix this, Any suggestion will also do.
THANKS
Special thanks to #SMi, With his GuidLines i was able to solve my issue.
I knew that i had to clear the inner array at the end of the loop[But,didn't knew how to clear that.]
var add_it = AssetModel(rackName: AssetGroupName, rackDescription: AssetGroupDescription, totalNoAssets: totalAssets, EntityId: entityId, rackItems: assetContents)
assetData.append(add_it)
assetContents.removeAll()
All i had to do is use the .removeAll() method to clear the assetContents Array.

How to handle json error in loop or stop it

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

how to extract a json object using swift?

JSON function:
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError)
if (parseError == nil){
if let coupon_list = json as? [String: AnyObject]{
if let coupons = coupon_list["data"] as? [AnyObject]{
for (var i = 0; i < coupons.count ; i++ ){
if let coupon_obj = coupons[i] as? NSDictionary{
let location: AnyObject? = coupon_obj.objectForKey("location")
//the print the value location
println(location)
//I just want to get the number keys before the value of the location
this is my Json object where you can see that
{
brand = "Mang Inasal";
category = (
2
);
desc = "Mang Inasal Salmonella Giveaway";
discount = 50;
"end_date" = 1443369600;
id = 2;
imgs = (
"http://mymegamobile.com/savvy/halo2x.png",
"http://mymegamobile.com/savvy/bar_filter.png",
"http://mymegamobile.com/savvy/bar_mega.png",
"http://mymegamobile.com/savvy/box1.png",
"http://mymegamobile.com/savvy/box2.png"
);
location = {
1435307555 = Baguio;
};
name = "Mang Inasal Halo Halo";
stamp = "2015-09-02 14:04:38";
"start_date" = 1438012800;
}
the result of the object structure is above.
How can I get the value of 1435307555 in my location?
You can do it this way:
let yourObject = location?.objectForKey("165952298") as! String
for (key,value) in coupon_list {
println(key)
}
This way you'll get all keys from the JSON
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as! NSDictionary
if (parseError == nil) {
for (var i = 0; i < json.count ; i++ ) {
let location: AnyObject? = ((json)["location"] as! NSDictionary)["1435307555"]
//the print the value location
println(location)
}
}

Resources