SOLVED: I just added 'for-in'
I hope that somebody will help me.
How can I display cells with a different elements inside satisfying "sequence" order. The cells should be arranged in any order and any number of each custom cell. I mean that first cell should to show first item type, second cell - second item type, third cell - first item type, fourth cell - first item.
It depends on the sequence from json data.
I have a json file with next structure (check the sequence array, that what I need):
{
"data": [{
"name": "first item",
"data": {
"text": "first item"
}
}, {
"name": "second item",
"data": {
"url": "picture.png"
}
}
],
"sequence": ["first item", "second item", "first item", "first item"]
}
I created My class for json parsing and other methods:
class MyClass {
private let jsonStr = "url adress"
var items = [ModelItem]()
var jsonData: Object!
func jsonParsing(completionHandler: #escaping (([ModelItem], Error?) -> Void)) {
guard let url = URL(string: jsonStr) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { DispatchQueue.main.async {completionHandler([], error)}
return
}
do {
self.jsonData = try JSONDecoder().decode(Object.self, from: data)
DispatchQueue.main.async {
if let name = self.jsonData?.data[0].data.text {
let firstItem = FirstItemModel(text: name)
self.items.append(firstItem)
}
if let pictureUrl = self.jsonData?.data[1].data.url {
let secondItem = SecondItemModel(pictureUrl: pictureUrl)
self.items.append(secondItem)
}
}
DispatchQueue.main.async {completionHandler(self.items, nil)}
} catch {
print("Error serializing json:", error)
}
} .resume()
}
}
Struct for JSON:
struct Object: Decodable {
let data: [ArrayModelData]
let sequence: [String]
}
Enum for multiple cell types:
enum ModelItemType: String {
case firstItem
case secondItem
}
protocol ModelItem {
var type: ModelItemType { get }
var rowCount: Int { get }
var sectionTitle: String { get }
}
extension ModelItem {
var rowCount: Int {
return 1
}
}
UITableView methods:
func numberOfSections(in tableView: UITableView) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items[section].rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.section]
switch item.type {
case .firstItem:
...
case .secondItem:
...
return UITableViewCell()
}
It would be better to keep a separate variables holding the each type of items.
var one: [ItemA]?
var two: [ItemB]?
var seq: [Int] = [1,2,1,1]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return one.count + two.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
var data: [Item]
if seq[row] == 1 {
data = one[row]
} else {
data = two[row]
}
// ..
}
All items ItemA, ItemB types can conform to a protocol say Item.
protocol Item {
}
class ItemA: Item {}
class ItemB: Item {}
Related
With the help of some videos I was able to parse my Firestore data into an array of arrays, but now I'm having a bit of trouble figuring out how to use this data to populate my tableview.
The idea is to use the 'dow' field for the Sections and the 'workouts' field for the Rows.
If I print the first index of my array, this is the output that I'm getting...
[Days(dow: "Tuesday", workouts: [Effortflex.Workouts(workout: "Back")]), ..., ...]
I feel like I'm missing a step here. Can someone assist me with this please.
self.loadData { (Bool) in
if Bool == true {
print(self.dataArray[0])
self.dayCount = self.dataArray.count
}
}
struct Workouts {
var workout : String
}
struct Days {
var dow : String
var workouts : [Workouts]
var dictionary: [String : Any] {
return ["dow" : dow]
}
}
extension Days {
init?(dictionary: [String : Any], workouts : [Workouts]) {
guard let dow = dictionary["dow"] as? String else { return nil }
self.init(dow: dow, workouts: workouts)
}
}
//MARK: - Load Data
func loadData(completion: #escaping (Bool) -> ()){
let group = DispatchGroup()
self.rootCollection.getDocuments (completion: { (snapshot, err) in
if let err = err
{
print("Error getting documents: \(err.localizedDescription)");
}
else {
guard let dayDocument = snapshot?.documents else { return }
for day in dayDocument {
group.enter()
self.rootCollection.document(day.documentID).collection("Workouts").getDocuments { (snapshot, err) in
var workouts = [Workouts]()
guard let workoutDocument = snapshot?.documents else { return }
for workout in workoutDocument {
let workoutString = workout.data()["workout"] as! String
let newWorkout = Workouts(workout: workoutString)
workouts.append(newWorkout)
}
let dayTitle = day.data()["dow"] as! String
let newDay = Days(dow: dayTitle, workouts: workouts)
self.dataArray.append(newDay)
group.leave()
}
}
}
group.notify(queue: .main){
completion(true)
}
})
}
I made an example that you can use as a basis to be able to use your structure.
Make your array into a list and persist in the scope of your class so that the methods of the tableView can access it. You can transform as follows:
let dataList = dataArray.flatMap{$0}
Then use the data to display on the tableView
func numberOfSections(in tableView: UITableView) -> Int {
dataList.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList[section].workouts.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataList[section].dow
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "testcell", for: indexPath)
cell.textLabel?.text = dataList[indexPath.section].workouts[indexPath.row].workout
return cell
}
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
}
My scenario, I am trying to load JSON data into UITableView. Here, the problem is my JSON having multiple array of multiple values. I need to get array keys as a Tableview section names and its all values load into relevant cell. I am using codable method for easy JSON data process. Now, how to do array key names (School, Office, etc,) into section and its values relevant cell.
My JSON
https://api.myjson.com/bins/r763z
My Codable
struct Root : Decodable {
let status : Bool
let data: ResultData
}
struct ResultData : Decodable {
let school, college, office, organisation, central : [Result]
}
struct Result : Decodable {
let id, name, date : String
let group : [String]
}
My JSON Decoder Code
func loadJSON(){
let urlPath = "https://api.myjson.com/bins/r763z"
let url = NSURL(string: urlPath)
let session = URLSession.shared
let task = session.dataTask(with: url! as URL) { data, response, error in
guard data != nil && error == nil else {
print(error!.localizedDescription)
return
}
do {
let decoder = JSONDecoder()
self.tableData = try decoder.decode(DivisionData.self, from: data!) // How to get section values and cell values and load table data
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch { print(error) }
}
task.resume()
}
Expected Output
To display the JSON in sections efficiently you have to decode the JSON into a struct with a title member
struct Root : Decodable {
let status : Bool
let sections : [Section]
private enum CodingKeys : String, CodingKey { case status, data }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
status = try container.decode(Bool.self, forKey: .status)
let data = try container.decode([String:[Result]].self, forKey: .data)
sections = data.compactMap{ return $0.value.isEmpty ? nil : Section(title: $0.key, result: $0.value) }
}
}
struct Section {
let title : String
let result : [Result]
}
struct Result : Decodable {
let id, name, date : String
let group : [String]
}
Declare a data source array
var sections = [Section]()
Assign the result to the array
do {
let decoder = try JSONDecoder().decode(Root.self, from: data!)
let status = decoder.status
if status == true {
sections = decoder.sections
DispatchQueue.main.async {
self.tableView.reloadData()
}
} else {
}
} catch { print(error) }
The relevant table view data source methods are
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].result.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
let item = sections[indexPath.section].result[indexPath.row]
// Update the UI
}
Side note: Name your structs with more meaningful names. For example an array is supposed to be named with something in plural form (like in my previous suggestion)
Just use the different arrays for the different sections.
var tableData: ResultData?
override func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let tableData = tableData else { return 0 }
switch section {
case 0:
return tableData.school.count
case 1:
return tableData.college.count
case 2:
return tableData.office.count
case 3:
return tableData.organisation.count
case 4:
return tableData.central.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "School"
case 1:
return "College"
case 2:
return "Office"
case 3:
return "Organisation"
case 4:
return "Central"
default:
return nil
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
// Get item
var item: Result?
switch section {
case 0:
item = tableData?.school[indexPath.row]
case 1:
item = tableData?.college[indexPath.row]
case 2:
item = tableData?.office[indexPath.row]
case 3:
item = tableData?.organisation[indexPath.row]
case 4:
item = tableData?.central[indexPath.row]
default:
break
}
if let item = item {
// Configure the cell...
}
return cell
}
To fetch your data, you need to use a URLSession like that:
func fetchData() {
guard let url = URL(string: "https://api.myjson.com/bins/r763z") else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("An error occurred: \(error)")
} else if let data = data, let response = response as? HTTPURLResponse, response.statusCode == 200 {
let decoder = JSONDecoder()
do {
let json = try decoder.decode(Root.self, from: data)
tableData = json.data
// Reload table view
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print("Decoding error: \(error)")
}
}
}
task.resume()
}
I've got this JSON from an API:
{
"oldest": "2019-01-24T00:00:00+00:00",
"activities": [
{
"message": "<strong>Henrik</strong> didn't resist a guilty pleasure at <strong>Starbucks</strong>.",
"amount": 2.5,
"userId": 2,
"timestamp": "2019-05-23T00:00:00+00:00"
},
{
"message": "<strong>You</strong> made a manual transfer.",
"amount": 10,
"userId": 1,
"timestamp": "2019-01-24T00:00:00+00:00"
}
]
}
It has a lote more activities. How can I access it and fill my cells with its data? So far I've got this code:
MainViewController:
struct Activities: Decodable {
var oldest: String
var activities: [Activity]
}
struct Activity: Decodable {
var message: String
var amount: Float
var userId: Int
var timestamp: String
}
class MainTableViewController: UITableViewController, UITableViewDataSourcePrefetching {
var activityList: [Activities] = []
var activity: [Activity] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.prefetchDataSource = self
let activitiesJSONURLString = "https://qapital-ios-testtask.herokuapp.com/activities?from=2016-05-23T00:00:00+00:00&to=2019-05-23T00:00:00+00:00"
guard let activitiesURL = URL(string: activitiesJSONURLString) else { return }
URLSession.shared.dataTask(with: activitiesURL) { (data, response, err) in
// perhaps check err
// also perhaps check response status 200 OK
guard let data = data else { return }
do {
// Activities
let activities = try JSONDecoder().decode(Activities.self, from: data)
} catch let jsonErr {
print("Error serializing json: ", jsonErr)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}.resume()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activityList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ActivityCell", for: indexPath) as! MainTableViewCell
return cell
}
// Prefetching
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
// if indexPaths.contains(where: isLoadingCell) {
// viewModel.fetchModerators()
// }
}
}
But I think something is off. Or I have no clue on how to start. I could really use some help or any tips you can give me. Please and thank you!
First of all the naming of the structs is pretty confusing. Name the root object with something unrelated like Response or Root.
And we are going to decode the timestamps as Date
struct Root: Decodable {
var oldest: Date
var activities: [Activity]
}
struct Activity: Decodable {
var message: String
var amount: Float
var userId: Int
var timestamp: Date
}
Second of all as the data is received in all the conformance to UITableViewDataSourcePrefetching is pointless. Remove it and delete also the prefetchRowsAt method.
Declare only one data source array and name it activities
var activities = [Activity]()
and delete
var activityList: Activities!
In the completion handler of the data task decode Root and assign the activities array to the data source array
do {
// Activities
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let result = try decoder.decode(Root.self, from: data)
self.activities = result.activities
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print("Error serializing json: ", error)
}
The table view data source methods are
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ActivityCell", for: indexPath) as! MainTableViewCell
let activity = activities[indexPath.row]
// assign the activity data to the UI for example
// cell.someLabel = activity.amount
return cell
}
Because you are using the activityList to determine the number of rows, I'm assuming that you want to use the data from activityList in order to populate your ActivityCells. That is, unless, you meant for activityList to be a single instance of Activities instead of an array of Activities, in which case you would likely use activityList.activities.count in order to determine the number of rows. In either case, lets just call the array of data you want to use to fill the cells activityList.
In this case, you should make sure to update activityList to the activities that you have fetched from the API. Once you have the activityList, you can then use reloadData which will trigger your table view delegate methods. In tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) you can then use activityList in order to update the dequeued cell.
Something like this might be what you want:
class MainTableViewController: UITableViewController, UITableViewDataSourcePrefetching {
var activityList: Activities!
var activity: [Activity] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.prefetchDataSource = self
let activitiesJSONURLString = "https://qapital-ios-testtask.herokuapp.com/activities?from=2016-05-23T00:00:00+00:00&to=2019-05-23T00:00:00+00:00"
guard let activitiesURL = URL(string: activitiesJSONURLString) else { return }
URLSession.shared.dataTask(with: activitiesURL) { (data, response, err) in
// perhaps check err
// also perhaps check response status 200 OK
guard let data = data else { return }
do {
// Activities
let activities = try JSONDecoder().decode(Activities.self, from: data)
self.activityList = activities
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch let jsonErr {
print("Error serializing json: ", jsonErr)
}
}.resume()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activityList.activities.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ActivityCell", for: indexPath) as! MainTableViewCell
if let activity = activityList?[indexPath.row] {
// UPDATE CELL ACCORDING TO activity
}
return cell
}
}
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
}
}