My JSON looks like this and data is not coming from the server:
[
{
"emp_id": "1",
"fname": "Shreya",
"lname": "Shah",
"email_id": "shreyashah#gmail.com",
"password": "shreya123",
"date_of_birth": "14/03/1995",
"gender": "Female",
"street1": "Arbudgiri Society",
"street2": "Nr.Rambaug Road",
"city": "Ahmedabad",
"zipcode": "380005",
"country": "India",
"country_code": "+91",
"phone_no": "456544545",
"emp_img": "employeeImages/shreyashah#gmail.com_services-pic2.jpg",
"emp_desig": "PHP Developer",
"emp_skills": "html,php,css,jquery,javascript",
"emp_edu": "BCA,MCA",
"emp_exp": "3years",
"emp_notice_period": "30days",
"emp_lang": "english,hindi,gujarati"
},
{
"emp_id": "2",
"fname": "Harish",
"lname": "Verma",
"email_id": "harishverma#gmail.com",
"password": "harish123",
"date_of_birth": "22/07/1994",
"gender": "Female",
"street1": "Satyam Skyline",
"street2": "Nr.Sola Cross Roads",
"city": "Ahmedabad",
"zipcode": "380005",
"country": "India",
"country_code": "+91",
"phone_no": "964783214",
"emp_img": "employeeImages/harishverma#gmail.com_services-pic2.jpg",
"emp_desig": "iOS Team Lead",
"emp_skills": "objective-c,swift",
"emp_edu": "BCA,MCA",
"emp_exp": "3years",
"emp_notice_period": "30days",
"emp_lang": "english,hindi,gujarati"
}
]
My code in VIEWCONTROLLER code where i have decoded the json and used it in my file:
import UIKit
struct EmployeeDisplayData: Decodable {
let emp_img: String
let fname: String
let emp_desig: String
let emp_exp: String
let country: String
let emp_notice_period: String
}
class UserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var mainTableView: UITableView!
let URL_GET_DATA = "http://172.16.1.22/Get-Employee-API/get-employee/"
var employeeArray = [EmployeeDisplayData]()
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.delegate = self
self.mainTableView.dataSource = self
getEmployee()
// Do any additional setup after loading the view, typically from a nib.
// Do any additional setup after loading the view.
}
func getEmployee(){
let empURL = URL(string: "http://172.16.1.22/Get-Employee-API/get-employee/")
URLSession.shared.dataTask(with: empURL!) { (data, response, error) in
do
{
if error == nil
{
self.employeeArray = try JSONDecoder().decode([EmployeeDisplayData].self, from: data!)
for mainArr in self.employeeArray
{
DispatchQueue.main.async {
self.mainTableView.reloadData()
}
}
print("****Employee Data****\(self.employeeArray)")
}
}
catch
{
print("Error in get JSON Data Employee\(error)")
}
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return employeeArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:EMpTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EMpTableViewCell") as! EMpTableViewCell
let empData = employeeArray[indexPath.row]
cell.lblOne.text = empData.fname
cell.lblTwo.text = empData.emp_desig
cell.lblThree.text = empData.emp_exp
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
Can someone help me with this error I have no idea what does this error mean I have seen the same type error most of the places and tried to solve it but still the same error from the server
my postman
]4
I got the same error and I searched a lot by changing contentType and many more things but none is fixed it. PostMan Raw and Preview Tab response gives me idea where the exact issue.
Raw
Preview
This error occur because of Connected to MySQL text beginning of response. so inform your developer about this, he will solve this and may be the error solve.
Related
Hello good afternoon to everyone.
I hope you are doing very well despite the situation we are going through.
I tell you my problem.
I am trying to save in an array, a series of data that is selected from a tableView through a JSON.
That is, the tableView shows some data available to select, the ones that are selected I want to save them in an array but when I select a data in the tableView my app crashes and shows me a breakpoint "Thread 1: signal SIGABRT"
And in the console I get this:
Could not cast value of type 'MallConcierge.DetallesIntereses' (0x10ca9be10) to 'NSString' (0x7fff86d8bbb0).
I hope you can help me, I attach the classes from where I download the data, the details and the class where I connect the tableView.
InteresesModelo.swift (in this class is where I download the data in JSON)
import UIKit
protocol InteresesModeloProtocol: class{
func interesesDownload (interest: NSArray)
}
class InteresesModelo: NSObject {
weak var delegate: InteresesModeloProtocol!
let urlPath = "http://localhost:8888/mallconcierge/API-movil/interests.php"
func interestDownload(){
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.ephemeral)
URLCache.shared.removeAllCachedResponses()
let task = defaultSession.dataTask(with: url){
(data, response, error) in
if error != nil{
print("Error al descargar datos")
}else{
print("Datos descargados")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data){
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
}catch let error as NSError{
print(error)
}
var jsonElement = NSDictionary()
let detalles = NSMutableArray()
for i in 0 ..< jsonResult.count{
jsonElement = jsonResult[i] as! NSDictionary
let detalle = DetallesIntereses()
let idInteres = jsonElement["idInteres"]
let nombreInteres = jsonElement["interesNombre"]
detalle.idInteres = idInteres as? String
detalle.nombreInteres = nombreInteres as? String
detalles.add(detalle)
}
DispatchQueue.main.async(execute: { ()-> Void in
self.delegate.interesesDownload(interest: detalles)
})
}
}
DetallesIntereses.swift
import UIKit
class DetallesIntereses: NSObject {
var idInteres: String?
var nombreInteres: String?
override init() {
}
init(idInteres: String, nombreInteres:String) {
self.idInteres = idInteres
self.nombreInteres = nombreInteres
}
override var description: String{
return "idInteres: \(idInteres), nombreInteres: \(nombreInteres)"
}
}
InteresesViewController.swift
import UIKit
class InteresesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, InteresesModeloProtocol {
var selectIntereses = [String]()
var feedInterests: NSArray = NSArray()
// var selectInterests: DetallesIntereses = DetallesIntereses()
var items=[String]()
#IBOutlet var listaInteresesTableView: UITableView!
func interesesDownload(interest: NSArray) {
feedInterests = interest
self.listaInteresesTableView.reloadData()
}
override func viewDidLoad() {
self.listaInteresesTableView.isEditing = true
self.listaInteresesTableView.allowsMultipleSelectionDuringEditing = true
self.listaInteresesTableView.delegate = self
self.listaInteresesTableView.dataSource = self
let interesesModelo = InteresesModelo()
interesesModelo.delegate = self
interesesModelo.interestDownload()
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedInterests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "celInterests", for: indexPath) as! InteresesTableViewCell
let interest: DetallesIntereses = feedInterests[indexPath.row] as! DetallesIntereses
cell.lblNombreIntereses!.text = interest.nombreInteres
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectDeselectCell(tableView: listaInteresesTableView, indexPath: indexPath)
print("Seleccionado")
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.selectDeselectCell(tableView: listaInteresesTableView, indexPath: indexPath)
print("Deseleccionado")
}
func selectDeselectCell(tableView: UITableView, indexPath: IndexPath){
self.selectIntereses.removeAll()
if let arr = listaInteresesTableView.indexPathsForSelectedRows{
for index in arr{
selectIntereses.append(feedInterests[indexPath.row] as! String)
}
}
print(selectIntereses)
}
#IBAction func seleccionarIntereses(_ sender: Any){
print(selectIntereses)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
The JSON
[
{
"idInteres": "1",
"interesNombre": "Moda Mujer"
},
{
"idInteres": "3",
"interesNombre": "Moda Hombre"
},
{
"idInteres": "4",
"interesNombre": "Belleza"
},
{
"idInteres": "5",
"interesNombre": "Relojes y Joyería"
},
{
"idInteres": "6",
"interesNombre": "Hogar/Interiorismo"
},
{
"idInteres": "7",
"interesNombre": "Gastronomía"
},
{
"idInteres": "8",
"interesNombre": "Entretenimiento"
},
{
"idInteres": "9",
"interesNombre": "Wellness"
}
]
I hope you can help me, please.
I thank you all
There's lots of little stuff going on here. I've tried to highlight as I make edits with //<-- Here.
By far the biggest issue is using the untyped Objective-C NSArray instead of using a typed Swift array. By switching to that, you can get useful type errors.
I had to make a couple of assumptions about what you wanted to do, but this should get you started.
I've left the original JSON decoding for the most part, but I'd strongly suggest you look into using Codable instead of JSONSerialization unless you have a compelling reason not to.
protocol InteresesModeloProtocol : AnyObject {
func interesesDownload (interest: [DetallesIntereses]) //<-- Here
}
class InteresesModelo: NSObject {
weak var delegate: InteresesModeloProtocol!
let urlPath = "http://localhost:8888/mallconcierge/API-movil/interests.php"
func interestDownload(){
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.ephemeral)
URLCache.shared.removeAllCachedResponses()
let task = defaultSession.dataTask(with: url){
(data, response, error) in
if error != nil{
print("Error al descargar datos")
}else{
print("Datos descargados")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data){
var jsonResult = [[String:String]]()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [[String : String]]
}catch let error as NSError{
print(error)
}
let detalles = jsonResult.map { jsonElement -> DetallesIntereses in
let detalle = DetallesIntereses(idInteres: jsonElement["idInteres"], nombreInteres: jsonElement["interesNombre"])
return detalle
}
DispatchQueue.main.async {
self.delegate.interesesDownload(interest: detalles)
}
}
}
struct DetallesIntereses { //<-- Here -- no reason for this to be an `NSObject`
var idInteres: String?
var nombreInteres: String?
}
class InteresesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, InteresesModeloProtocol {
var selectIntereses = [DetallesIntereses]() //<-- Here
var feedInterests: [DetallesIntereses] = [] //<-- Here
var items = [String]()
#IBOutlet var listaInteresesTableView: UITableView!
func interesesDownload(interest: [DetallesIntereses]) { //<-- Here
feedInterests = interest //<-- Here
self.listaInteresesTableView.reloadData()
}
override func viewDidLoad() {
self.listaInteresesTableView.isEditing = true
self.listaInteresesTableView.allowsMultipleSelectionDuringEditing = true
self.listaInteresesTableView.delegate = self
self.listaInteresesTableView.dataSource = self
let interesesModelo = InteresesModelo()
interesesModelo.delegate = self
interesesModelo.interestDownload()
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedInterests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "celInterests", for: indexPath) as! InteresesTableViewCell
let interest: DetallesIntereses = feedInterests[indexPath.row] //<-- Here
cell.lblNombreIntereses!.text = interest.nombreInteres
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectDeselectCell(tableView: listaInteresesTableView, indexPath: indexPath)
print("Seleccionado")
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.selectDeselectCell(tableView: listaInteresesTableView, indexPath: indexPath)
print("Deseleccionado")
}
func selectDeselectCell(tableView: UITableView, indexPath: IndexPath){
self.selectIntereses.removeAll()
selectIntereses.append(feedInterests[indexPath.row]) //<-- Here
print(selectIntereses)
}
#IBAction func seleccionarIntereses(_ sender: Any){
print(selectIntereses)
}
}
I am attempting to parse data from an api into a tableView with Sections. The end result would be a section title that corresponds with a month and rows with lists of videos that were posted for the month. The videos may not include a poster or description.
I tried to implement a for in loop function to update the model after retrieving the data, which worked great until I started trying to implement sections. I can print the json response to the console and receive the full response.
Here is a sample of the original JSON Structure:
{
"page": {
"type": "videos",
"sections": [{
"title": "September",
"videos": [{
"title": "Some Video",
"description": "Video Description",
"poster": "",
"url": "url"
}]
}, {
"title": "August 2019",
"videos": [{
"title": "Some Video",
"description": "",
"poster": "Some Image",
"url": "url"
}, {
"title": "Some Video",
"description": "No Description",
"poster"",
"url": "url"
}]
}]
}
}
Here is my Model:
struct Root: Decodable {
let page: Page
}
struct Page: Decodable {
let type: String
let sections: [VideoSection]
}
struct VideoSection: Decodable {
let title: String
let videos: [Video]
}
struct Video: Decodable {
let videoTitle: String
let videoDescription: String?
let poster: String?
let url: String
enum CodingKeys: String, CodingKey {
case videoTitle = "title"
case videoDescription = "description"
case poster = "poster"
case url = "url"
}
}
Here is may Networking call with Parsing:
func getVideoData(url: String){
guard let videoUrl = URL(string: "Video_URL") else { return }
URLSession.shared.dataTask(with: videoUrl) { (data, response, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let responseData = try decoder.decode(Root.self, from: data)
DispatchQueue.main.async {
self.videoTableView.reloadData()
}
} catch let err {
print("Error", err)
}
}.resume()
}
Here is my tableView:
var allvideosArray = [Video]()
var allSectionsArray = [VideoSection]()
var rootArray: Root?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customVideoCell", for: indexPath) as! CustomVideoCell
cell.videoDescriptionPlaceholder.text = Video.CodingKeys.videoDescription.rawValue
cell.videoTitlePlaceholder.text = Video.CodingKeys.videoTitle.rawValue
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return allSectionsArray[section].title
}
func numberOfSections(in tableView: UITableView) -> Int {
return allSectionsArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allvideosArray.count
}
When I attempt to print(responseData.page.sections.videos) I receive the error "Value of type'[VideoSection]' has no member 'videos,' which leads me to believe the issue has to do with the [videos] array inside of the [sections] array.
You can try
var page:Page?
let responseData = try decoder.decode(Root.self, from: data)
self.page = responseData.page
DispatchQueue.main.async {
self.videoTableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customVideoCell", for: indexPath) as! CustomVideoCell
let item = page!.sections[indexPath.section].videos[indexPath.row]
cell.videoDescriptionPlaceholder.text = item.videoDescription
cell.videoTitlePlaceholder.text = item.videoTitle
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return page?.sections[section].title
}
func numberOfSections(in tableView: UITableView) -> Int {
return page?.sections.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return page?.sections[section].videos.count ?? 0
}
I'm working with Swiftyjson in Swift 2.3. I've been able to parse json arrays into a UITableview with no problem until I got the following json response:
{
"CAR": [
{
"SID": "1",
"NAME": "BMW",
},
{
"SID": "2",
"NAME": "MERCEDES",
},
],
"BIKE": [
{
"SID": "3",
"NAME": "KAWASAKI",
},
{
"SID": "4",
"NAME": "HONDA",
},
]
}
QUESTION How do I parse "CAR" and "BIKE" into tableview sections and have their items under each section? I've managed to get the "keys" using:
// Other Code
let json = JSON(data)
for (key, subJson) in json {
self.array.append(key)
}
print(self.array)
["CAR", "BIKE"]
I wanted to know how to loop through each section and get their items properly. Any help would be great!
Since you haven't shown where you are getting your json data from, I have tested this by having your JSON above in a .json file. Also this doesn't use SwiftyJSON but you will be able to modify the syntax to get the same result.
class TableViewController: UITableViewController {
var tableData = Dictionary<String,Array<Dictionary<String,String>>>()
var sections = Array<String>()
override func viewDidLoad() {
super.viewDidLoad()
load(file: "document")
}
func load(file:String) {
guard let path = Bundle.main.path(forResource: file, ofType: "json") else { return }
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return }
guard let json = try? JSONSerialization.jsonObject(with: data) else { return }
guard let dict = json as? Dictionary<String,Array<Dictionary<String,String>>> else { return }
self.tableData = dict
self.sections = dict.keys.sorted()
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return self.sections.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let key = self.section[section]
return key
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let key = self.section[indexPath.section]
return self.tableData[key]?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// Configure the cell...
let key = self.section[indexPath.section]
let cellData = self.tableData[key]?[indexPath.row]
cell.textLabel?.text = cellData?["NAME"]
cell.detailTextLabel?.text = "SID: \(cellData?["SID"] ?? "Unknown")"
return cell
}
}
This is how it looks on an iPhone.
in my app i am first time using AlamofireObjectMapper.
So i am mapping api response data in one class and then i want to use that data.
So here is my code that how i map object
extension OrderListViewController
{
func get_order_list()
{
let url = "\(OrderURL)get_New_order_byPharmacy"
let param : [String : AnyObject] = [
"pharmacyId" : "131"
]
Alamofire.request(.GET, url, parameters: param, encoding: .URL).responseObject { (response:Response<OrderList, NSError>) in
let OrderList = response.result.value
print(OrderList!.Message)
}
}
}
and here is the class where i saving my data
class OrderList: Mappable {
var Message : String!
var Status : Int!
var result:[OrderResult]?
required init?(_ map: Map){
}
func mapping(map: Map) {
Message <- map["Message"]
Status <- map["Status"]
result <- map["Result"]
}
}
now in my OrderListViewController i want to use this data so how can i use this??
class OrderListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var table_OrderList: UITableView!
override func viewDidLoad() {
slideMenuController()?.addLeftBarButtonWithImage(UIImage(named: "ic_menu_black_24dp")!)
slideMenuController()?.addRightBarButtonWithImage(UIImage(named: "ic_notifications_black_24dp")!)
get_order_list()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
}
for example i want to print message value in my tableview cell label. so how can i get that value form OrderList?
Thanks slava its give me some solution. but my json response give me array. So how can i manage it? and i want to return in numberofrowinSetcion is count of array so how can i do this. please see my updated question.
here is my api response.
{
"Status": 1,
"Message": "records are available",
"Result": [
{
"id": 30162,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-11T10:45:00.6779848",
"created": "11 May 2016"
},
{
"id": 30170,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T07:01:00.6968385",
"created": "12 May 2016"
},
{
"id": 30171,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T09:12:53.5538349",
"created": "12 May 2016"
},
{
"id": 30172,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T09:46:09.4329398",
"created": "12 May 2016"
},
{
"id": 30173,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-12T11:26:58.3211678",
"created": "12 May 2016"
},
{
"id": 30178,
"status_id": 2,
"status_type": "New Order",
"created_date": "2016-05-16T07:34:19.9128517",
"created": "16 May 2016"
}
]
}
You need a local variable in your controller to store all the received information that will be used to fill the table. Something like that should do:
class OrderListViewController: ... {
private var orderList: OrderList? // <- the local variable needed
...
}
extension OrderListViewController {
func get_order_list() {
...
Alamofire
.request(...)
.responseObject { (response:Response<OrderList, NSError>) in
switch response.result {
case .Success(let value):
self.orderList = value // <- fill the local variable with the loaded data
self.tableView.reloadData()
case .Failure(let error):
// handle error
}
}
}
...
}
extension OrderListViewController: UITableViewDataSource {
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell
// I assume 'OrderList_Cell' class has outlet for status type named 'statusTypeLabel' and OrderResult.statusType is of type String
if let orderList = orderList, orderResults = orderList.result {
cell.statusTypeLabel.text = orderResults[indexPath.row].statusType // <- use of the locally stored data
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let orderList = orderList, orderResults = orderList.result {
return orderResults.count
} else {
return 0
}
}
}
Note: the code should be correct in case you receive the single object in JSON from backend.
If backend sends the array of objects - you'll need to use array to store local data (private var listOfOrderLists: [OrderList]) and use Alamofire.request(...).responseArray(...) instead. But the idea about local variable is still the same.
typealias FailureHandler = (error: AnyObject) -> Void
typealias SuccessHandler = (result: AnyObject) -> Void
class WebServiceManager: NSObject {
class func getDataFromService(mehodName:String,success:(result:AnyObject)->(), apiError:(FailureHandler))
{
let url = "\(OrderURL)get_New_order_byPharmacy"
let param : [String : AnyObject] = [
"pharmacyId" : "131"
]
alamoFireManager!.request(.GET, url)
.responseJSON { response in
print(response.response!)
print(response.result)
CommonFunctions.sharedInstance.deactivateLoader()
switch response.result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
guard let _ = JSON as? NSMutableArray else {
apiError(error: "")
return
}
let listOfItem:NSMutableArray = NSMutableArray()
for (_, element) in adsArray.enumerate() {
let adsItem = Mapper<OrderList>().map(element)
listOfItem.addObject(adsItem!)
}
success(result:listOfItem)
case .Failure(let data):
print(data)
}
}
}
class OrderListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var table_OrderList: UITableView!
var listOFOrder:NSMutableArray =[]
override func viewDidLoad() {
slideMenuController()?.addLeftBarButtonWithImage(UIImage(named: "ic_menu_black_24dp")!)
slideMenuController()?.addRightBarButtonWithImage(UIImage(named: "ic_notifications_black_24dp")!)
WebServiceManager.getDataFromService("", success: { (result) in
listOFOrder = result as NSMutableArray
self.recordTable?.reloadData()
}) { (error) in
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listOFOrder.count
}
}
I wrote this code to read country at table view from this JSON file :
JSON:
[5]
0: {
"country": "Afghanistan"
"code": "AF"
}-
1: {
"country": "Åland Islands"
"code": "AX"
}-
2: {
"country": "Albania"
"code": "AL"
}-
3: {
"country": "Algeria"
"code": "DZ"
}-
4: {
"country": "American Samoa"
"code": "AS"
}
My code :
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableCountryView: UITableView!
var json_url = "........ my url here ......... "
var TableData:Array< datastruct > = Array < datastruct >()
enum ErrorHandler:ErrorType
{
case ErrorFetchingResults
}
struct datastruct
{
var country_name:String?
var country_code:String?
init(add: NSDictionary)
{
country_name = add["country"] as? String
country_code = add["code"] as? String
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableCountryView.dataSource = self
tableCountryView.delegate = self
get_data_from_url(json_url)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let data = TableData[indexPath.row]
cell.textLabel?.text = data.country_name! + " - " + data.country_code!
return cell
}
func get_data_from_url(url:String)
{
let url:NSURL = NSURL(string: url)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
dispatch_async(dispatch_get_main_queue(), {
self.extract_json(data!)
return
})
}
task.resume()
}
func extract_json(jsonData:NSData)
{
let json: AnyObject?
do {
json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
} catch {
json = nil
return
}
if let list = json as? NSArray
{
for (var i = 0; i < list.count ; i++ )
{
if let data_block = list[i] as? NSDictionary
{
TableData.append(datastruct(add: data_block))
}
}
do_table_refresh()
}
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.tableCountryView.reloadData()
return
})
}
}
This code is working true for the first JSON syntax but if I want to read sub-array like the syntax at the following JSON file , how I can edit that in my previous code.
JSON:
{
"Countries": [4]
0: {
"countryname": "Egypt"
"code": "20"
}-
1: {
"countryname": "India"
"code": "91"
}-
2: {
"countryname": "United States"
"code": "1"
}-
3: {
"countryname": "Turkey"
"code": "90"
}-
}
Also I have the button at my storyboard and I want to show this table view of country when clicking on this button and then choose one country and close this table and show the result on the button , I know this easy but I started to learn IOS from 2 weeks only, I hope if you can give me advice in these cases.