Swift Retrieve Data with Nested Array - ios

I am trying to pass data into variable by displaying it(NameList and BasketDetail). But the basket data is empty(BasketDetail). How can i solve this (Output:Retrieve data: [“name”: Mike, “basket”: <__NSArray0 0x28112c060()])?
Firebase node;
"Pro_" : {
"-MsVcfY7pZI74r0E1ULD" : {
"basket" : {
"-Mruf-UdXxpLK0l8Qgw4" : {
"cat" : "Tech",
"info" : "iOS",
"orderid" : "Ref_1",
},
"-MszuLj3cxm_gE9m-VPO" : {
"cat" : "Tech",
"info" : "Android",
"orderid" : "Ref_2",
}
},
"name" : "-Mike",
}
}
My function;
private func populateNameLists() {
ref = Database.database().reference()
self.ref.child(“Pro_”).observeSingleEvent(of:.value) { (snapshot) in
self.nameLists.removeAll()
let nameListDictionary = snapshot.value as? [String:Any] ?? [:]
for (key,_) in nameListDictionary {
if let nameListDictionary = nameListDictionary[key] as? [String:Any] {
if let nameList = NameList(nameListDictionary) {
self.nameLists.append(nameList)
print(“Retrieve data:”, try! nameList.toDictionary())
}}}}}
Output(Basket's empty ???)
Retrieve data: [“name”: Mike, “basket”: <__NSArray0 0x28112c060()]
Name List
typealias JSONDictionary = [String:Any]
class NameList : Codable {
var basket :[BasketDetail] = [BasketDetail]()
var name: String!
init(name:String ) {
self.name = name
}
init?(_ dictionary :[String:Any]) {
guard let name = dictionary[“name”] as? String else {
return nil
self.name = name
let basketItemsDictionary = dictionary[“basket”] as? [JSONDictionary]
if let dictionaries = basketItemsDictionary {
self.basket = dictionaries.compactMap(BasketDetail.init)
}}}
Basket Detail
class BasketDetail : Codable{
var cat : String
var info : String
var orderid : String
init(cat :String, info :String, orderid :String) {
self.cat = cat
self.info = info
self.orderid = orderid
}
init?(dictionary :JSONDictionary) {
guard let cat = dictionary["cat"] as? String else {
return nil
}
guard let info = dictionary["info"] as? String else {
return nil
}
guard let orderid = dictionary["orderid"] as? String else {
return nil
}
self.cat = cat
self.info = info
self.orderid = orderid
}}

Related

Swift: display arrayobject to tableView

im trying to dispaly array object come from api response as [[String: Any]] at table view
and thats my struct
class CategoriesDep: NSObject {
var depName: String
var depImage: String
var subName = [subData]()
init?(dict: [String: JSON]) {
guard let image = dict["main_department_image"]?.imagePath, !image.isEmpty else { return nil }
self.depImage = image
self.depName = (dict["main_department_name"]?.string)!
}
struct subData {
var dep: String
init(dic: [String: Any]) {
self.dep = dic["sub_department_name"] as! String
}
}
}
Please check below code to parse your json
class CategoriesDep: NSObject {
var depName: String
var depImage: String
var subName = [subData]()
init?(dict: [String: Any]) {
guard let image = dict["main_department_image"] as? String, !image.isEmpty else { return nil }
self.depImage = image
self.depName = (dict["main_department_name"] as? String)!
subName = []
for subDict in (dict["sub_depart"] as? [[String:Any]] ?? []){
subName.append(subData(dic: subDict))
}
}
}
struct subData {
var dep: String
var image :String
var id : String
init(dic: [String: Any]) {
self.dep = dic["sub_department_name"] as! String
self.image = dic["sub_department_image"] as! String
self.id = dic["sub_department_id"] as! String
}
}
and if you want to access subdata struct out side of CategoriesDep class then declare structure outside CategoriesDep class
Parse your given json Respoise like
let json = [
[ "sub_depart" : [
[ "sub_department_name" : "hos", "sub_department_id" : "6", "sub_department_image" : "23.jpg"
]
],
"main_department_id" : "2",
"main_department_name" : "main ",
"main_department_image" : "14.jpg"
],
]
var catDepart : [CategoriesDep] = []
for dict in json {
catDepart.append(CategoriesDep(dict: dict)!)
}
print(catDepart[0].subName[0].dep)
You could use Codabel protocol to be more swifty ;) and cleaning up the code.
let jsonString = "[{\"sub_depart\" : [ {\"sub_department_name\" : \"hos\", \"sub_department_id\" : \"6\", \"sub_department_image\" : \"23.jpg\" } ], \"main_department_id\" : \"2\", \"main_department_name\" : \"main \", \"main_department_image\" : \"14.jpg\"}]"
struct CategoriesDep: Codable {
let mainDepartmentName: String
let mainDepartmentImage: String
let mainDepartmentId: String
var subDepart: [SubData] = []
}
struct SubData: Codable {
let subDepartmentName: String
let subDepartmentImage: String
let subDepartmentId: String
}
if let jsonData = jsonString.data(using: .utf8) {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
var departments: [CategoriesDep]? = try? decoder.decode([CategoriesDep].self, from: jsonData)
...
}
Note the decoder.keyDecodingStrategy = .convertFromSnakeCase here which is mapping the underscore (snake_case) API property names to your camelCase ones.
If you need different property names you have to implement CodingKeys enum to map them.
For more detailed information check this link.

POST request in Alamofire swift 4

am unable to make nested dict, please help me out
{
"OneStopFlight" : "false",
"TokenId" : "86839fb9-ed93-46d3-b480-c58dbc441838",
"AdultCount" : "1",
"InfantCount" : "0",
"JourneyType" : "1",
"EndUserIp" : "192.168.10.10",
"DirectFlight" : "false",
"Segments" : [
{
"PreferredDepartureTime" : "2018-06-27T00:00:00",
"Origin" : "PNQ",
"EndUserIp" : "192.168.10.10",
"Destination" : "VNS",
"FlightCabinClass" : "1"
}
],
"ChildCount" : "0"
}
If you want to create such dictionary as did showed above , you can create it easily as below
let segmentDict : [[String:Any]] = [
[
"PreferredDepartureTime" : "2018-06-27T00:00:00",
"Origin" : "PNQ",
"EndUserIp" : "192.168.10.10",
"Destination" : "VNS",
"FlightCabinClass" : "1"
]
]
let paramDict : [String:Any] = [
"OneStopFlight" : "false",
"TokenId" : "86839fb9-ed93-46d3-b480-c58dbc441838",
"AdultCount" : "1",
"InfantCount" : "0",
"JourneyType" : "1",
"EndUserIp" : "192.168.10.10",
"DirectFlight" : "false",
"Segments" : segmentDict,
"ChildCount" : "0"
]
let segmentWithMultipleDict : [[String:Any]] = [
[
"PreferredDepartureTime" : "2018-06-27T00:00:00",
"Origin" : "PNQ",
"EndUserIp" : "192.168.10.10",
"Destination" : "VNS",
"FlightCabinClass" : "1"
],
[
"PreferredDepartureTime" : "2018-06-27T00:00:00",
"Origin" : "PNQ",
"EndUserIp" : "192.168.10.10",
"Destination" : "VNS",
"FlightCabinClass" : "1"
]
]
In case if you want to Deque such data
struct dequeResponse
{
var OneStopFlight : String = ""
var TokenId : String = ""
var AdultCount : String = ""
var InfantCount : String = ""
var JourneyType : String = ""
var EndUserIp : String = ""
var DirectFlight : String = ""
var Segments : [segment] = []
var ChildCount : String = ""
func getDataFromJSON(_ data: [String:Any]) -> dequeResponse{
var myResponseValues = dequeResponse()
if let value = data["OneStopFlight"] as? String {
myResponseValues.OneStopFlight = value
}
if let value = data["TokenId"] as? String {
myResponseValues.TokenId = value
}
if let value = data["AdultCount"] as? String {
myResponseValues.AdultCount = value
}
if let value = data["InfantCount"] as? String {
myResponseValues.InfantCount = value
}
if let value = data["JourneyType"] as? String {
myResponseValues.JourneyType = value
}
if let value = data["EndUserIp"] as? String {
myResponseValues.EndUserIp = value
}
if let value = data["DirectFlight"] as? String {
myResponseValues.DirectFlight = value
}
if let value = data["Segments"] as? [[String:Any]] {
let newSegment = segment()
myResponseValues.Segments = newSegment.getDataFromJSON(value)
}
if let value = data["ChildCount"] as? String {
myResponseValues.ChildCount = value
}
return myResponseValues
}
}
struct segment {
var PreferredDepartureTime : String?
var Origin : String?
var EndUserIp : String?
var Destination : String?
var FlightCabinClass : String?
func getDataFromJSON(_ data: [[String:Any]]) -> [segment] {
var segmentAray = [segment]()
for i in 0..<data.count {
var myCurrentSegment = segment()
if let value = data[i]["PreferredDepartureTime"] as? String {
myCurrentSegment.PreferredDepartureTime = value
}
if let value = data[i]["Origin"] as? String {
myCurrentSegment.Origin = value
}
if let value = data[i]["EndUserIp"] as? String {
myCurrentSegment.EndUserIp = value
}
if let value = data[i]["Destination"] as? String {
myCurrentSegment.Destination = value
}
if let value = data[i]["FlightCabinClass"] as? String {
myCurrentSegment.FlightCabinClass = value
}
segmentAray.append(myCurrentSegment)
}
return segmentAray
}
}
Usage
var jsonObject = dequeResponse()
jsonObject = jsonObject.getDataFromJSON(paramDict)
print(jsonObject.Segments)
Note If this doesn't meet your requirement please edit question with more detail

How to remove the dictionary in an array which id was equal to the value comparing in swift 3?

Here I am having two values which is 46 and 47 in customFlashId and customLikeId here i am getting dynamically and I need to compare the values in categories model class children data array and I just need to remove which id matches with new comparing value that needs to be removed from model class and need to update it according to new results can anyone help me how to resolve this ?
I tried this
self.categoriesModel?.childrenData = (self.categoriesModel?.childrenData.filter({$0.id == self.customLikeId || $0.id == self.customFlashId}))!
and another one I tried is this
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
self.categoriesModel = Categories(json: jsonObj as [String : AnyObject])
DispatchQueue.main.async {
for item in 0...(self.categoriesModel?.childrenData.count)! - 1 {
if self.categoriesModel?.childrenData[item].childrenData != nil || self.categoriesModel?.childrenData[item].childrenData.count != 0 {
if self.categoriesModel?.childrenData[item].id == Int(self.customFlashId!) || self.categoriesModel?.childrenData[item].id == Int(self.customLikeId!) {
}
else {
if self.categoriesModel?.childrenData[item].includeInMenu == true {
self.categoriesModel?.childrenData.append((self.categoriesModel?.childrenData[item])!)
}
}
}
}
Here is my model class data
struct Categories {
let id : Int?
let parentId : Int?
let name : String?
let isActive : Bool?
let position : Int?
let level : Int?
let includeInMenu : Bool?
let parentLevelname : String?
let urlKey : String?
let brand : Any?
let image : String?
let productCount : Int?
var childrenData = [Categories]()
init?(json : [String:Any]) {
self.id = json["id"] as? Int ?? 0
self.parentId = json["parent_id"] as? Int ?? 0
self.name = json["name"] as? String ?? ""
self.isActive = json["status"] as? Bool ?? false
self.position = json["position"] as? Int ?? 0
self.level = json["level"] as? Int ?? 0
self.includeInMenu = json["include_in_menu"] as? Bool ?? false
self.parentLevelname = json["parent_level_name"] as? String ?? ""
self.urlKey = json["url_key"] as? String ?? ""
self.brand = json["brand"]
self.image = json["image"] as? String ?? ""
self.productCount = json["product_count"] as? Int ?? 0
if let customAttribute = json["children_data"] as? [[String: AnyObject]] {
var result = [Categories]()
for obj in customAttribute {
result.append(Categories(json: obj )!)
}
self.childrenData = result
} else {
self.childrenData = [Categories]()
}
}
}
and my category url follows as http://www.json-generator.com/api/json/get/cflnNlfhxK?indent=2

How to make model class for following JSON response in swift iOS

Hi i am beginner for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below
MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please
JsonResponse:-
[{
"_id" : "5470def9e0c0be27780121d7",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
"name" : "Mondo",
"hasVip" : false,
"location" : {
"city" : "Madrid"
}
}, {
"_id" : "540b2ff281b30f3504a1c72f",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
"name" : "Teatro Kapital",
"hasVippler" : false,
"location" : {
"address" : "Atocha, 125",
"city" : "Madrid"
}
}, {
"_id" : "540cd44581b30f3504a1c73b",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
"name" : "Charada",
"hasVippler" : false,
"location" : {
"address" : "La Bola, 13",
"city" : "Madrid"
}
}]
mapping:
Club:-
class Club {
var id: String = ""
var name: String = ""
var imageUrl: String = ""
var hasVip: Bool = false
var desc: String = ""
var location: [Location] = []
}
Location:-
class Location {
var country: String = ""
var city: String = ""
var address: String = ""
var zip: String = ""
var underground: [String] = []
}
NSURlSession code:-
class BackGroundPostCall: NSObject {
var delegate:PostProtocol?
func callPostService(url:String,params:NSDictionary){
print("url is===>\(url)")
let request = NSMutableURLRequest(URL: NSURL(string:url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
print("Response: \(json)")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
}
For mapping you can use Alamofire's extension ObjectMapper.
Ex:
[{
"_id" : "5470def9e0c0be27780121d7",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
"name" : "Mondo",
"hasVip" : false,
"location" : {
"city" : "Madrid"
}
}, {
"_id" : "540b2ff281b30f3504a1c72f",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
"name" : "Teatro Kapital",
"hasVippler" : false,
"location" : {
"address" : "Atocha, 125",
"city" : "Madrid"
}
}, {
"_id" : "540cd44581b30f3504a1c73b",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
"name" : "Charada",
"hasVippler" : false,
"location" : {
"address" : "La Bola, 13",
"city" : "Madrid"
}
}]
And mapper class:
import ObjectMapper
class Location: Mappable {
var address: String?
var city: String?
required init?(map: Map){
}
func mapping(map: Map) {
address <- map["address"]
city <- map["city"]
}
}
class Club: Mappable {
var id: String?
var imageUrl: Int?
var name: String?
var hasVip: Bool = false
var location: Location?
required init?(map: Map){
}
func mapping(map: Map) {
id <- map["_id"]
imageUrl <- map["imageUrl"]
name <- map["name"]
hasVip <- map["hasVippler"]
location <- map["location"]
}
}
And this way very flexible and transparent to use.
https://github.com/Alamofire/Alamofire
https://github.com/tristanhimmelman/AlamofireObjectMapper
Using example:
Alamofire.request(URL).responseArray { (response: DataResponse<[Club]>) in
let clubs = response.result.value
if let clubs = clubs {
for club in clubs {
print(club.name)
print(club.location.city)
}
}
}
You can make model class using this url : http://www.jsoncafe.com/
open this link and put your json in JSON tab and select any Code Template that is you want. and there is you can also add prefix class name and root class name if you want other wise it is optional. and last click on generate button, your json class is ready.!!
Step1: Create your model like below.
class Club {
var id: String = ""
var name: String = ""
var imageUrl: String = ""
var hasVip: Bool = false
var desc: String = ""
var location = Location()
init?(dictionary:[String:Any],location: Location) {
guard let id = dictionary["_id"],
let name = dictionary["name"],
let imageUrl = dictionary["imageUrl"],
let hasVip = dictionary["hasVippler"]
else {
return nil
}
self.id = id
self.name = name
self.imageUrl = imageUrl
self.hasVip = hasVip
self.location = location
}
}
}
class Location {
var country: String = ""
var city: String = ""
var address: String = ""
var zip: String = ""
init?(dictionary:[String:Any]) {
guard let country = dictionary["country"],
let city = dictionary["city"],
let address = dictionary["address"],
let zip = dictionary["zip"]
else {
return nil
}
self.country = country
self.city = city
self.address = address
self.zip = zip
}
}
}
Step2: Declare your array as below.
var myTargetArray = [Club]()
Step3: Json Parsing.
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
print("Response: \(json)")
for club in json {
if let clubDictionary = club as? NSDictionary {
if let locationDict = clubDictionary["location"] as? NSDictionary{
if let location = Location(dictionary: locationDict) {
if let clubObj = Club(dictionary: clubDictionary, location:location) {
myTargetArray.append(clubObj)
}
}
}
}
}
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
Note: I removed underground array from location model since your json data does not contain it.
Finally you can use your target array as your tableview source. Happy coding...
Model class:
class test : Unboxable {
let id : String
let imageURl : String
let name : String
let hasVip : Bool
let city : String
required init(unboxer: Unboxer) throws {
self.id = unboxer.unbox(key: "id") ?? ""
self.imageURl = unboxer.unbox(key: "imageUrl") ?? ""
self.name = unboxer.unbox(key: "name") ?? ""
self.hasVip = unboxer.unbox(key: "hasVip") ?? false
self.city = (unboxer.unbox(key: "city") ?? nil)!
}
}
parse json:
if let object = json as? [Any] {
// json is an array
var data :[test] = []
for respObject in object {
var dict = respObject as? Dictionary<String,AnyObject>
dict?["city"] = dict?["location"]?["city"] as AnyObject
let result1: [test] = try unbox(dictionaries: [dict!])
data.append(contentsOf: result1)
}
print(data)
For more details follow
https://github.com/JohnSundell/Unbox
**Api call with model class, swiftyjson and alamofire,Pod install alamofire and swiftyjson libraries, create collection view cell class, Create a class and write the following code
**
import UIKit
import Alamofire
import SwiftyJSON
var myResponse : JSON? = nil
var users : [reasonList] = []
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
feedbackApi()
}
func feedbackApi(){
DispatchQueue.main.async {
let url = URL(string: "--------")
let urlRequest = URLRequest(url: url!)
Alamofire.request(urlRequest)
.responseJSON { response in
switch response.result{
case.success(let data):
print("dddd :",data)
self.myResponse = JSON(data)
print(self.myResponse as Any)
let a = self.myResponse![0]["reasonList"]
print(a)
for i in 0..<a.count{
let single = reasonList(reasonListJson: a[i])
self.users.append(single)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failure(let error):
print("dddd",error)
}
}
}
}
}
create a model class
import Foundation
import SwiftyJSON
class user{
var deviceId = String()
var deviceName = String()
var deviceLocationId = Int()
var locationName = String()
var welcomeText = String()
var reason=[reasonList]()
init(userJson:JSON) {
self.deviceId = userJson["deviceId"].stringValue
self.deviceName = userJson["deviceName"].stringValue
self.deviceLocationId = userJson["deviceLocationId"].intValue
self.locationName = userJson["locationName"].stringValue
self.welcomeText = userJson["welcomeText"].stringValue
self.reason = [reasonList(reasonListJson: userJson["reason"])]
}}
class reasonList{
var reason = String()
var id = Int()
init(reasonListJson:JSON) {
self.reason = reasonListJson["reason"].stringValue
self.id = reasonListJson["id"].intValue
]}
**create a collection view in view **
import UIKit
import Alamofire
import SwiftyJSON
class ReasonViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
//DelayCall()
// Do any additional setup after loading the view.
}
func DelayCall() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
_ = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController")as! HomeViewController
self.navigationController?.popViewController(animated: true)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return users.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReasonCollectionViewCell", for: indexPath) as! ReasonCollectionViewCell
let useee = users[indexPath.row]
print(useee)
cell.reasonLabel.text = useee.reason
return cell
}}
You can make model class using this url : https://www.json4swift.com/
Open this link and paste your JSON and select from below option you want. Click generate, it will generate class files you can download and used it in your project.

How To increase index of Array when the value is Dynamic (Swift)

I am Getting a Dynamic Array which Consist (Dictionary with Array ) and want to increase the Index of Array and will go on to Next Dictionary on action.
After Parsing The Value in swapLibs
var currentQuizIndex = 0
func Dataparsed() {
ServiceManager.service(ServiceType.POST, path: urslStr, param: nil, completion: { (sucess, response, error, code) -> Void in
if (code == 200) {
let QuizData = (swapLibs?.valueForKey("quiz") as! NSArray)
let quizData = playInfo.PlayQuizInfo(QuizData[self.currentQuizIndex] as? NSDictionary)
self.playQuizArray.addObject(quizData)
self.playQuizTitle?.text = quizData.quizQuestion
self.playQImage.sd_setImageWithURL(NSURL(string: quizData.quizQImage!))
self.QNumber?.text = "\(self.Qno)/\(self.noofQuestion)"
}
})
}
And The Modal is
class playInfo: NSObject {
var quizId : String? = ""
var quizQId : String? = ""
var quizQImage : String? = ""
var quizQuestion : String? = ""
var quizType : String? = ""
var quizIndex : String? = ""
class func PlayQuizInfo(dict: NSDictionary?) -> playInfo {
let Pinfo = playInfo()
Pinfo.WrapPlayQuiz(dict)
return Pinfo
}
func WrapPlayQuiz(dict: NSDictionary?) {
if dict == nil {
return
}
self.quizId = dict!.objectForKey("quizId") as? String
self.quizIndex = dict!.objectForKey("index") as? String
self.quizQImage = dict!.objectForKey("QuesImage") as? String
self.quizQuestion = dict!.objectForKey("question") as? String
self.quizType = dict!.objectForKey("Type") as? String
self.quizQId = dict!.objectForKey("questionId") as? String
}
}
Here is Structure
{
"quiz":[
{
"quizId":"7295",
"QuesImage":"http:\/\/proprofs.com\/api\/ckeditor_images\/man-approaches-woman1(1).jpg",
"question":"How do you know him?",
"questionId":"216210",
"Type":"PQ",
"index":4,
"keys":[
{
"answerId":"8266",
"option":"He's in one or more of my classes, and we're good friends.",
"AnsImage":"Image Not Available"
},
{ },
{ },
{ },
{ }
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
Each Dictionary is Containing same Key As above
Any Help Will Be Appreciated.Thanks.
As I don't have ServiceManager at my end so I have created this code hypothetically. It might solve you issue of saving all data in to one array. It also adds keys in to array as an object.
EDIT 1 : correct QuizKey object array formation. Let me know if any kind of error occurs, as I am unable to test it at my end.
Edit 2: I have made a general ViewController its working perfectly.Try running this View Controller file and you will see the results.
class TestVC: UIViewController {
//An Array similar to the response you are getting from the server
var response:[AnyObject] = [
[
"quizId" : "1111",
"QuesImage" : "http://proprofs.com/api/ckeditor_images/man-approaches-woman1(1).jpg",
"question" : "How do you know him?",
"questionId" : "216210",
"Type" : "PQ",
"index" : 4,
"keys":[
[
"answerId":"8266",
"option":"He's in one or more of my classes, and we're good friends.",
"AnsImage":"Image Not Available"
],
[
"answerId":"8266",
"option":"He's in one or more of my classes, and we're good friends.",
"AnsImage":"Image Not Available"
],
[
"answerId":"8266",
"option":"He's in one or more of my classes, and we're good friends.",
"AnsImage":"Image Not Available"
]
]
],
[
"quizId" : "2222",
"QuesImage" : "http://proprofs.com/api/ckeditor_images/man-approaches-woman1(1).jpg",
"question" : "How do you know him?",
"questionId" : "216210",
"Type" : "PQ",
"index" : 4,
"keys":[
[
"answerId":"8266",
"option":"He's in one or more of my classes, and we're good friends.",
"AnsImage":"Image Not Available"
],
[
"answerId":"8266",
"option":"He's in one or more of my classes, and we're good friends.",
"AnsImage":"Image Not Available"
],
[
"answerId":"8266",
"option":"He's in one or more of my classes, and we're good friends.",
"AnsImage":"Image Not Available"
]
]
]
]
var playQuizArray:[playInfo]! = []
override func viewDidLoad() {
super.viewDidLoad()
print(response)
for dict in response {
self.playQuizArray.append(playInfo.PlayQuizInfo(dict as? [String:AnyObject]))
}
print(self.playQuizArray)
let quiz = self.playQuizArray[0]
print("quizId \(quiz.quizId)")
print("keyAnswerId \(quiz.quizKeys![0].keyAnswerId)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class playInfo: NSObject {
var quizId : String? = ""
var quizQId : String? = ""
var quizQImage : String? = ""
var quizQuestion : String? = ""
var quizType : String? = ""
var quizIndex : String? = ""
//quizKeys will contain quiz array
var quizKeys : [QuizKey]? = []
class func PlayQuizInfo(dict: [String:AnyObject]?) -> playInfo {
let Pinfo = playInfo()
Pinfo.WrapPlayQuiz(dict)
return Pinfo
}
func WrapPlayQuiz(dict: [String:AnyObject]?) {
if dict == nil {
return
}
self.quizId = dict!["quizId"] as? String
self.quizIndex = dict!["index"] as? String
self.quizQImage = dict!["QuesImage"] as? String
self.quizQuestion = dict!["question"] as? String
self.quizType = dict!["Type"] as? String
self.quizQId = dict!["questionId"] as? String
//add key object array to the quizKeys
if let arrKeys = dict!["keys"] as? [AnyObject] {
for arr in arrKeys {
let key:QuizKey = QuizKey.QuizKeyInfo(arr as? [String : AnyObject])
self.quizKeys?.append(key)
}
}
}
}
class QuizKey: NSObject {
var keyAnswerId : String? = ""
var keyOption : String? = ""
var keyAnsImage : String? = ""
class func QuizKeyInfo(dict: [String:AnyObject]?) -> QuizKey {
let QKeys = QuizKey()
QKeys.WrapQuizKeys(dict)
return QKeys
}
func WrapQuizKeys(dict: [String:AnyObject]?) {
if dict == nil {
return
}
self.keyAnswerId = dict!["answerId"] as? String
self.keyOption = dict!["option"] as? String
self.keyAnsImage = dict!["AnsImage"] as? String
}
}

Resources