acmobile acmobile - 5 months ago 46
Swift Question

How to properly create a class to hold data from JSON with Alamofire and SwiftyJSON

I'm trying to create a class to hold data from webservice sent as JSON. Here is the JSON I'm getting back from the server:

[
{
"weekSchedule":[
{
"weekDay":"sunday",
"listening":[
{
"textName":"Programa de teste 1",
"textPresenter":"Apresentador",
"timeStartHour":"08:00:00",
"timeEndHour":"23:59:00",
"textDescription":"Descri\u00e7\u00e3o do programa ",
"textGuest":"Dr. Lair Ribeiro",
"urlImage":"file:\/\/servidor\/lampp\/webservice\/img\/happy.png"
},
{
"textName":"Teste 2",
"textPresenter":"Teste",
"timeStartHour":"00:00:00",
"timeEndHour":"00:00:00",
"textDescription":"",
"textGuest":"",
"urlImage":"file:\/\/servidor\/lampp\/webservice\/img\/happy.png"
}
]
},
{
"weekDay":"monday",
"listening":[
{
"textName":"Programa de teste 1",
"textPresenter":"Apresentador",
"timeStartHour":"08:00:00",
"timeEndHour":"23:59:00",
"textDescription":"Descri\u00e7\u00e3o do programa ",
"textGuest":"Dr. Lair Ribeiro",
"urlImage":"file:\/\/servidor\/lampp\/webservice\/img\/happy.png"
},
{
"textName":"Programa teste marco",
"textPresenter":"Marco",
"timeStartHour":"08:30:00",
"timeEndHour":"09:30:00",
"textDescription":"Apenas um programa para testar o json",
"textGuest":"Jason",
"urlImage":"file:\/\/servidor-ubuntu\/lampp\/webservice\/img\/happy.png"
}
]
}
]
}
]


Here are the model classes I'm creating (Need help here!)

import Foundation
import SwiftyJSON

class Show: ResponseJSONObjectSerializable {

var name: String?
var description: String?
var host: String?
var guest: String?
var startTime: String?
var endTime: String?
var urlImage: String?

required init(json: JSON) {
self.name = json["textName"].string
self.description = json["textDescription"].string
self.host = json["textPresenter"].string
self.guest = json["textGuest"].string
self.startTime = json["timeStartHour"].string
self.endTime = json["timeEndHour"].string
self.urlImage = json["urlImage"].string
}

required init() {}
}

class ShowArray: ResponseJSONObjectSerializable {

var weekday: String?
var showArray: [Show]?

required init?(json: JSON) {

self.weekday = json["weekDay"].string

if let jsonArray = json["listening"].array {
self.showArray = []

for json in jsonArray {
let instance = Show(json: json)
self.showArray?.append(instance)
}
}
}

}

class ScheduleArray: ResponseJSONObjectSerializable {

var scheduleArray: [ShowArray]?

required init?(json: JSON) {

if let weekArray = json["weekSchedule"].array {
self.scheduleArray = []

for weekDay in weekArray {
let instance = ShowArray(json: weekDay)
self.scheduleArray?.append(instance!)
}
}
}
}


The Alamofire function to make the http request:

func getWeeklyShedule(completionHandler: (Result<ScheduleArray, NSError>) -> Void) {

alamofireManager.request(RCAppRouter.GetSchedule()).responseObject {
(response: Response<ScheduleArray, NSError>) in

guard response.result.isSuccess else {
print("Error fetching schedule: \(response.result.error!)")
return
}

completionHandler(response.result)
}
}


Then in my view controller I need to hold the listings on an array of Show

var listings = [Show]()
RCAPIManager.sharedInstance.getWeeklyShedule {
(result) in

guard result.error == nil else {
print("Error")
return
}

guard let fetchedSchedule = result.value else {
print("No schedule fetched")
return
}

self.listings = fetchedSchedule.scheduleArray ???

}


This is where I got stuck, how can I loop through the object to store the data from listings to my array of Show?

Any tips on how to refactor my code to achieve, The expected result is a segmented control for each day o the week, when pressed I'll use it as a filter to display the appropriated information.

Thanks!!!

Answer

This might not be the prettiest way but it'll work.

if let responseArray = response as? NSArray {
    for i in 0..<responseArray.count {
    let showDic = responseArray[i] as! NSDictionary
    let dayOfWeek = showDic["weekday"] as! String
    let showArray = showDic["listening"] as! NSArray
        switch dayOfWeek {
        case "sunday":
           addShowObjectsToArray(showArray, dailyShows: sundayArray)
        case "monday":
           addShowObjectsToArray(showArray, dailyShows: mondayArray)
        case "tuesday":
           addShowObjectsToArray(showArray, dailyShows: tuesdayArray)
        case "wednseday":
           addShowObjectsToArray(showArray, dailyShows: wednsedayArray)
        case "thursday":
           addShowObjectsToArray(showArray, dailyShows: thursdayArray)
        case "friday":
           addShowObjectsToArray(showArray, dailyShows: fridayArray)
        case "saturday":
           addShowObjectsToArray(showArray, dailyShows: saturdayArray)
        default:
        }
    }

func addShowObjectsToArray(shows: NSArray, dailyShows: NSArray) {
    for show in shows {
        let showObject = Show(show)
        dailyShows.append(showObject)
    }
}
Comments