UITableView Null Value - swift

I have a list of JSON data downloaded from server:
(DataModal.swift)
class DataModal {
var orderAutoid: Int?
var orderId: String?
var orderName: String?
var orderQty: String?
var orderStatus: String?
init(bOrder_autoid: Int, bOrder_id: String, bOrder_name: String, bOrder_qty: String, bOrder_status: String){
self.orderAutoid = bOrder_autoid
self.orderId = bOrder_id
self.orderName = bOrder_name
self.orderQty = bOrder_qty
self.orderStatus = bOrder_status
}
(OrderStructureDownloadProtocol.swift)
protocol OrderStructureDownloadProtocol: class {
func newItemDownload(items: Array<Any>)
}
....
var jsonElement = Dictionary<String, Any>()
var newOrders = Array<Any>()
for i in 0..<jsonResult.count {
jsonElement = jsonResult[i] as! Dictionary
let newOrder_autoid = jsonElement["orderAutoid"] as? Int ?? 0
let newOrder_id = jsonElement["orderId"] as? String ?? ""
let newOrder_name = jsonElement["orderName"] as? String ?? ""
let newOrder_qty = jsonElement["orderQty"] as? String ?? ""
let newOrder_status = jsonElement["orderStatus"] as? String ?? ""
let newOrder = BMSDataModal(bOrder_autoid: newOrder_autoid, bOrder_id: newOrder_id, bOrder_name: newOrder_name, bOrder_qty: newOrder_qty, bOrder_status: newOrder_status)
newOrders.append(newOrder)
}
DispatchQueue.main.async (
execute: { () -> Void in
self.delegate.newItemDownload(items: newOrders as! Array<Any>)
})
(tableview.swift)
var newOrdersArray = [BMSDataModal]()
func newItemDownload(items: Array<Any>) {
newOrdersArray = items as! [BMSDataModal]
newOrderLookupTableView.reloadData()
}
(tableview.swift another part)
let cell = tableView.dequeueReusableCell(withIdentifier: "orderLookupCell", for: indexPath) as! NewOrderTableViewCell
let item = newOrdersArray[indexPath.row]
cell.newHMNumber?.text = item.orderId ?? "-"
cell.newMP?.text = item.orderName ?? "-"
cell.newQTY?.text = item.orderQty ?? "-"
return cell
}
having all the old NS-style changed. The app is running okay, there are some items that need to reset. As my data-source always contain Double, but I declared it as a String, as I won't deal with calculation so I treated it as 'String'.

Related

How to get Firebase data as a model in swift?

I am trying to get data from firebase and use it as a model that I created.
Here is my model;
class UserData{
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : [String:Competition] = [String:Competition]()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: String = ""
var name: String = ""
var users : [String:Int] = [:]
}
and this is my function;
func getFirebaseData() {
ref = Database.database().reference()
ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { (snapshot) in
if let snapshotValue = snapshot.value as? Dictionary<String,Any> {
//change userData with the snapshotValue
self.userData.nickname = snapshotValue["nickname"] as! String
self.userData.step_count = snapshotValue["step_count"] as! Int
self.userData.total_point = snapshotValue["total_point"] as! Int
self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
self.userData.competitions = snapshotValue["competitions"] as! [String:Competition]
//reload UI with userData
print(self.userData.competitions)
} else {
print("An error occured while assigning snapshotValue to userData")
}
}
}
This code gave me error like this;
Could not cast value of type '__NSDictionaryM' (0x1f47ada20) to 'StepCounterApp.Competition' (0x1004c06f0).
2021-01-02 23:05:49.985711+0300 StepCounterApp[32511:3685645] Could not cast value of type '__NSDictionaryM' (0x1f47ada20) to 'StepCounterApp.Competition' (0x1004c06f0).
but when i comment out the line included self.userData.competitions from getFirebaseData function, everything works fine.
What should I do? How can I use firebase data as a model?
Finally here is my firebase data;
The problem is in your data model. Declare your model data like this
class UserData {
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : Competition = Competition()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: String = ""
var name: String = ""
var users : [String:Int] = [:]
init() {
}
init(with dictionary: [String: Any]) {
self.end_date = dictionary["end_date"] as! String
self.gift = dictionary["gift"] as! String
self.id = dictionary["id"] as! String
self.name = dictionary["name"] as! String
self.users = dictionary["users"] as! [String:Int]
}
}
And inside the getFirebaseData funcation
self.userData.competitions = Competition(with: snapshotValue["competitions"] as! [String: Any])
The problem was in my data model and with the help of Raja Kishan's data model sugestion I fixed the problem.
First I changed the model little bit;
class UserData{
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : [String:Competition] = [String:Competition]()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: Int = 0
var name: String = ""
var users : [String:Int] = [:]
init() {
}
init(with dictionary: [String: Any]) {
self.end_date = dictionary["end_date"] as! String
self.gift = dictionary["gift"] as! String
self.id = dictionary["id"] as! Int
self.name = dictionary["name"] as! String
self.users = dictionary["users"] as! [String:Int]
}
}
Than I add a childSnapshot to my method so I can work directly the "competitions";
func getFirebaseData() {
ref = Database.database().reference()
ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { [self] (snapshot) in
if let snapshotValue = snapshot.value as? [String:Any] {
//change userData with the snapshotValue
self.userData.nickname = snapshotValue["nickname"] as! String
self.userData.step_count = snapshotValue["step_count"] as! Int
self.userData.total_point = snapshotValue["total_point"] as! Int
self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
//******
//This part of the coded added for to solve the problem starting from here
let childSnap = snapshot.childSnapshot(forPath: "competitions")
if let childSnapValue = childSnap.value as? [String:Any] {
childSnapValue.forEach { (element) in
self.userData.competitions.updateValue(Competition(with: element.value as! [String:Any]), forKey: element.key)
}
} else {
print("something wrong with the childSnap")
}
//to here
//******
} else {
print("An error occured while assigning snapshotValue to userData")
}
}
}

How to Clear Shared Dictionary which is causing saved values not to clear even when I login with other user

How can I clear the shared dictionary on logout in which I am saving login response?
Here is the code I am doing on getting status 1.
if(status == 1)
{
DispatchQueue.main.async {
GAReusableClass.sharedInstance.hideActivityIndicator()
UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
let Dict = self.mainDict[KData] as! [String: AnyObject]
print("self.DataDict", self.DataDict)
let User_ID = Dict[KUuid]as! String
print(User_ID)
let HMACSECRETKEY = self.deviceToken + "+" + User_ID
kHMACKey = HMACSECRETKEY
let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
print(HMACSECRETKEY)
UserDefaults.standard.setValue(cipher, forKey:HmacKey)
UserDefaults.standard.set(true, forKey: "isLogin")
GAloginUserInfo.shared.saveUserInfo(dict: Dict )
let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
self.navigationController?.pushViewController(tabar, animated: true)
}
Here is the shared dictionary which I am using to save the values of login response.
import UIKit
import Firebase
class GAloginUserInfo: NSObject {
var loginUserMobileNo : String?
var loginUserId : String?
var loginUserUuid : String?
var loginUserCountry : String?
var loginUserCountryCode : String?
var loginUserEmail : String?
var loginUserlatitude : String?
var loginUserLongitude : String?
var loginUserName : String?
var loginUserQrcode : String?
var loginUserProfilePic : String?
var isverify : String?
var loginPassword : String?
var dateOfBirth: String?
var earnedPoints:String?
var loginUserGender:String?
var loginUserFollowers:Int = 0
static let shared = GAloginUserInfo()
func saveUserInfo (dict : [String : AnyObject?] ) {
if let loginUserMobileNo = dict["mobile"] as? String {
self.loginUserMobileNo = loginUserMobileNo
}
if let loginUserId = dict["id"] as? String {
self.loginUserId = loginUserId
}
if let loginUserUuid = dict["uuid"] as? String {
self.loginUserUuid = loginUserUuid
print(loginUserUuid)
}
if let loginUserCountry = dict["country"] as? String {
self.loginUserCountry = loginUserCountry
}
if let loginUserCountryCode = dict["country_code"] as? String {
self.loginUserCountryCode = loginUserCountryCode
}
if let loginUserEmail = dict["email"] as? String {
self.loginUserEmail = loginUserEmail
}
if let loginUserProfilePic = dict["profile_pic"] as? String {
self.loginUserProfilePic = loginUserProfilePic
}
if let loginUserLongitude = dict["logitude"] as? String {
self.loginUserLongitude = loginUserLongitude
}
if let loginUserName = dict["name"] as? String {
self.loginUserName = loginUserName
}
if let loginUserQrcode = dict["qr_code"] as? String {
self.loginUserQrcode = loginUserQrcode
}
if let Password = dict["password"] as? String{
self.loginPassword = Password
}
if let dateOfBirth = dict["dob"] as? String{
self.dateOfBirth = dateOfBirth
}
if let earnedPoints = dict["points"] as? String{
let myDouble = Double(earnedPoints)
let doubleStr = String(format: "%.2f", myDouble!)
self.earnedPoints = doubleStr
}
if let loginUserGender = dict["gender"] as? String{
self.loginUserGender = loginUserGender
}
if let loginUserFollowers = dict["followersCount"] as? Int{
self.loginUserFollowers = loginUserFollowers
}
}
}
Actually, the problem is when I log out and log in again with some other user it still shows some values of the previous user. I am clearing the userdefaults on the logout function. but I don't know how to clear this type of shared dictionary.
Use removeObject(forKey:)
to remove the values stored from user defaults in Logout method
UserDefaults.standard.removeObject(forKey: MaindataKey)
UserDefaults.standard.removeObject(forKey: HmacKey)
UserDefaults.standard.set(false, forKey: "isLogin")
Create a method to remove the values from the singleton class like this
extension GAloginUserInfo {
func removeUserInfo() {
self.loginUserMobileNo = nil
self.loginUserId = nil
self.loginUserUuid = nil
self.loginUserCountry = nil
self.loginUserCountryCode = nil
self.loginUserEmail = nil
self.loginUserlatitude = nil
self.loginUserLongitude = nil
self.loginUserName = nil
self.loginUserQrcode = nil
self.loginUserProfilePic = nil
self.isverify = nil
self.loginPassword = nil
self.dateOfBirth = nil
self.earnedPoints = nil
self.loginUserGender = nil
self.loginUserFollowers = 0
}
}
and call this method in logout
GAloginUserInfo.shared.removeUserInfo()

How to connect to new viewController with data saved in struct model of other viewController

How can I get the data that in Struct model in new viewController
I got a viewController when i print the var in Struct model it appeare just fine.
I created New viewController trying to get the same data in otherview of that struct model but when i print it it give me nil
I tryied to make the model equal to the new model in the new viewController
MessageController View
var messages = [Message]()
var users = [Contact]()
var messagesDicionary = [String: Message]()
var testMSG : Message?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = self.messages[indexPath.row]
let chatPartnerId = message.chatPartnerId()
let ref = Database.database().reference().child("users").child(chatPartnerId)
ref.observe(.value) { (snap) in
if let dictinoary = snap.value as? [String: AnyObject] {
guard let email = dictinoary["email"] ,let profileimage = dictinoary["profileimage"], let userid = dictinoary["userid"], let username = dictinoary["username"] else {
return
}
var user = Contact()
user.userid = chatPartnerId
user.userid = chatPartnerId
let userValue = Contact.init(email: email as? String, username: username as? String, profileimage: profileimage as? String, userid: userid as? String)
self.users.append(userValue)
self.showChatControllerToUser(user: userValue)
print(message.receivername)
}
}
}
result of Print Optional("Omar")
ChatMessagesController View
var user :Contact?
var users = [Contact]()
var message: Message?
var messagesArray = [Message]()
func observeChatMessages() {
guard let uid = Auth.auth().currentUser?.uid else {
return
}
let userMessagesRef = Database.database().reference().child("usersmesssages").child(uid)
userMessagesRef.observe(.childAdded) { (snap) in
let messageId = snap.key
let messageRef = Database.database().reference().child("messages").child(messageId)
messageRef.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String:AnyObject] else {
return
}
let text = dictionary["text"] as? String
let receiverid = dictionary["receiverid"] as? String
let senderid = dictionary["senderid"] as? String
let time = dictionary["timestamp"] as? TimeInterval
let senderName = dictionary["sendername"] as? String
let receiverName = dictionary["receivername"] as? String
self.messagesArray.append(MessageValue)
self.chatTableView.reloadData()
print(self.message?.receivername)
})
}
}
result of print NIL
Message Model
struct Message {
var text: String?
var receiverid: String?
var senderid: String?
var timestamp: TimeInterval?
var sendername: String?
var receivername: String?
func chatPartnerId() -> String {
return (senderid == Auth.auth().currentUser?.uid ? receiverid : senderid)!
}
}
I tried to make in MessagesController
let chatMessage = ChatMessageController()
chatMessage.message = self.testMSG

Swift 4 Retrieving Data From Firebase Database

func retPost2(){
runNBPOST()
////////////////////////////////////1
var pic = [String]()
var p = Post(userId: "", postId: "", postType: "", description: "", Region: "", City: "", District: "", Street: "", Area: 0, View: "", TotalPrice: 0, Pictures: pic, StreetWidth: 0, PropertyType: "")
////// for to retrive all post
print(retNBPOST())
runNBPOST()
let nbpost = retNBPOST()
for i in 1..<nbpost{
postiiD = "Post(\(i))"
self._REF_BASE.child("Post").child(postiiD).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let UserID2 = value?["UserID"] as? String ?? ""
p.userId = UserID2
})
self._REF_BASE.child("Post").child("\("Post(\(i))")/Adress").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let Region = value?["Region"] as? String ?? ""
p.Region = Region
let City = value?["City"] as? String ?? ""
p.City = City
print(p.City)
let District = value?["District"] as? String ?? ""
p.District = District
let Street = value?["Street"] as? String ?? ""
p.Street = Street
let AdditionalNumber = value?["AdditionalNumber"] as? String ?? ""
p.AdditionalNumber = AdditionalNumber
let PostalCode = value?["PostalCode"] as? String ?? ""
p.PostalCode = PostalCode
let BuldingNo = value?["BuldingNo"] as? String ?? ""
p.BuldingNo = BuldingNo
})
self._REF_BASE.child("Post").child("\(postiiD)/PostInfo").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let postType = value?["PostType"] as? String ?? ""
p.postType = postType
print(p.postType)
let DateOfpost = value?["DateOfpost"] as? String ?? ""
p.dateOfpost = DateOfpost
let EndDateOfPost = value?["EndDateOfPost"] as? String ?? ""
p.endDateOfPost = EndDateOfPost
let NbOfShare = value?["NbOfShare"] as? String ?? ""
p.nbOfShare = Int(NbOfShare)!
let NbOfViews = value?["NbOfViews"] as? String ?? ""
p.nbOfViews = Int(NbOfViews)!
let LastUpdate = value?["LastUpdate"] as? String ?? ""
p.lastUpdate = LastUpdate
let Description = value?["Description"] as? String ?? ""
p.description = Description
let Publisher = value?["Publisher"] as? String ?? ""
p.publisher = Publisher
let ContactTime = value?["ContactTime"] as? String ?? ""
p.contactTime = ContactTime
let Payment = value?["Payment"] as? String ?? ""
p.payment = Payment
let TotalPrice = value?["TotalPrice"] as? String ?? ""
p.TotalPrice = Double(TotalPrice)!
let NearBy = value?["NearBy"] as? String ?? ""
p.NearBy = NearBy
let StreetWidth = value?["StreetWidth"] as? String ?? ""
p.StreetWidth = Double(StreetWidth)!
// let Discount = value?["Discount"] as? String ?? ""
// p.Discount =
})
self._REF_BASE.child("Post").child("\(postiiD)/Property").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let Area = value?["Area"] as? String ?? ""
p.Area = Double(Area)!
print(p.Area)
let View = value?["View"] as? String ?? ""
p.View = View
let FamilyOrSingle = value?["FamilyOrSingle"] as? String ?? ""
p.FamilyOrSingle = FamilyOrSingle
let Level = value?["Level"] as? String ?? ""
p.Level = Int(Level)!
let HouseAge = value?["HouseAge"] as? String ?? ""
p.HouseAge = Int(HouseAge)!
let LandType = value?["LandType"] as? String ?? ""
p.LandType = LandType
let MeterPrice = value?["MeterPrice"] as? String ?? ""
p.MeterPrice = Double(MeterPrice)!
let NbRoom = value?["NbRoom"] as? String ?? ""
p.NbRoom = Int(NbRoom)!
let NbGuestroom = value?["NbGuestroom"] as? String ?? ""
p.NbGuestroom = Int(NbGuestroom)!
let NbBathroom = value?["NbBathroom"] as? String ?? ""
p.NbBathroom = Int(NbBathroom)!
let NbBedroom = value?["NbBedroom"] as? String ?? ""
p.NbBedroom = Int(NbBedroom)!
let NbLivingroom = value?["NbLivingroom"] as? String ?? ""
p.NbLivingroom = Int(NbLivingroom)!
let NbKitchen = value?["NbKitchen"] as? String ?? ""
p.NbKitchen = Int(NbKitchen)!
let PropertyType = value?["PropertyType"] as? String ?? ""
p.PropertyType = PropertyType
let NbApartment = value?["NbApartment"] as? String ?? ""
p.NbApartment = Int(NbApartment)!
})
// complet
self._REF_BASE.child("Post").child("\(postiiD)/Amenities").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let LiftAvailability = value?["LiftAvailability"] as? String ?? ""
let KitchenAvailability = value?["KitchenAvailability"] as? String ?? ""
let FurnitureAvailability = value?["FurnitureAvailability"] as? String ?? ""
let CarageAvailability = value?["CarageAvailability"] as? String ?? ""
let SwimmingPoolAvailability = value?["SwimmingPoolAvailability"] as? String ?? ""
let ParkingAvailability = value?["ParkingAvailability"] as? String
let FiberOpticAvailability = value?["FiberOpticAvailability"] as? String
let FireplaceAvailability = value?["FireplaceAvailability"] as? String
let DiningroomAvailability = value?["DiningroomAvailability"] as? String
let LaundryAvailability = value?["LaundryAvailability"] as? String
let CentralAirAvailability = value?["CentralAirAvailability"] as? String
let BalconyAvailability = value?["BalconyAvailability"] as? String
let MaidRoomAvailability = value?["MaidRoomAvailability"] as? String
let DriverRoomAvailability = value?["DriverRoomAvailability"] as? String
let InternalStairAvailability = value?["InternalStairAvailability"] as? String
let BasementAvailability = value?["BasementAvailability"] as? String
})
arrpost.append(p)
}
}
func updateHomeView(post : Post){
totalPriceLb.text = "\(String(post.TotalPrice)) SR"
areaLb.text = String(post.Area)
AddressLb.text = "\(post.City) \(post.District) \(post.Street)"
imageName.image = UIImage(named: "HomePic.jpg")
if post.PropertyType == "Home" {
bathLb.text = String(post.NbBathroom)
BedLb.text = String(post.NbBedroom)
imageName.image = UIImage(named: "HomePic.jpg")
}else if post.PropertyType == "Apartment" {
bathLb.text = String(post.NbBathroom)
BedLb.text = String(post.NbBedroom)
imageName.image = UIImage(named: "ApartPic.jpg")
}else if post.PropertyType == "Land"{
bathLb.isHidden = true
BedLb.isHidden = true
imageName.image = UIImage(named: "LandPic.jpg")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
DataService.instance.retPost2()
// tableView.reloadData()
return DataService.instance.arrpost.count
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
func tableView
(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as! homecell
let post = DataService.instance.arrpost[indexPath.row]
// let post = DataServiceTemp.instance.getPosts()[indexPath.row]
cell.updateHomeView(post: post)
// tableView.reloadData()
return cell
}
I have a problem in my IOS App. I'm Using Firebase for saving & Retrieving data. All connections are good and the data is retrieved fine or sometimes incomplete.
And My Problem is when I run the app the views, labels, Pictures, etc are shown Empty at first when this components should show the data retrieved from firebase. I don't know what's the problem. Is it time or anything else? So the main problem is the components are shown empty before retrieving the data completely. I want to force the app to not show empty at first but showing the components with data.
I already use all method from google
https://firebase.google.com/docs/database/ios/read-and-write
Make hover UIView above the mainVC with a UIActivityIndicator until response comes from Firebase remove it

groupBy array by two values in swift

I'm using this extension of Array to groupBy:
func groupBy <U> (groupingFunction group: (Element) -> U) -> [U: Array] {
var result = [U: Array]()
for item in self {
let groupKey = group(item)
// If element has already been added to dictionary, append to it. If not, create one.
if result.has(groupKey) {
result[groupKey]! += [item]
} else {
result[groupKey] = [item]
}
}
return result
}
And trying to make a dictionary from teamId and rank (custom properties of my object from array).
self.items = myArray.groupBy {
team in
if team.rank == nil {
return team.teamId!
} else {
return team.rank!
}
}
My case looks something like this:
[{
"team_id": "4",
"team_name": "T16",
"rank": "3"
},
,{
"team_id": "4",
"team_name": "T16",
"rank": "2"
},
{
"team_id": "4",
"team_name": "T16",
"rank": "1"
}
,{
"team_id": "5",
"team_name": "T16",
"rank": null
}]
desired output:
let teams : [String: TeamItem] = [ "4" : TeamItem.rank3, "4-2" : TeamItem.rank2, "4-1" : TeamItem.rank1, "5" : TeamItem]
EDIT 2
func requestTeamData(listener:([TeamItem]) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let baseURL: String = self._appSettings.getPathByName(EndPoint.BASE_URL.rawValue) as! String
let paths: NSDictionary = self._appSettings.getPathByName(EndPoint.PATH.NAME.rawValue) as! NSDictionary
let teamPaths: NSDictionary = paths.objectForKey(EndPoint.PATH.TEAM.KEY.rawValue) as! NSDictionary
let path = teamPaths.valueForKey(EndPoint.PATH.TEAM.PATH.rawValue) as! String
request(.GET, baseURL + path, parameters:[:])
.responseCollection { (_, _, team: [TeamItem]?, error) in
if let team = team {
dispatch_async(dispatch_get_main_queue()) {
listener(team)
}
}
}
}
}
Calling the API, straightforward
DataProvider.getInstance().requestTeamData({(items:[TeamItem]) -> () in
//Getting the items from the API
})
EDIT 1
#objc final class TeamItem: Equatable, ResponseObjectSerializable, ResponseDictionarySerializable {
let firstName: String?
let lastName: String?
let seasonId: String?
let seasonName: String?
let teamId: String?
let teamName: String?
let rank: String?
let positionId: String?
let positionName: String?
let number: String?
let birthDate: String?
let birthPlace: String?
let citizenship: String?
let height: String?
let weight: String?
let maritalStatus: String?
let model: String?
let hobby: String?
let food: String?
let book: String?
let movie: String?
let wish: String?
let message: String?
let biography: String?
let imageURL: String?
let teamImageURL: String?
required init?(response: NSHTTPURLResponse, representation: AnyObject) {
self.firstName = representation.valueForKeyPath(EndPoint.Keys.Team.FirstName.rawValue) as? String
self.lastName = representation.valueForKeyPath(EndPoint.Keys.Team.LastName.rawValue) as? String
self.seasonId = representation.valueForKeyPath(EndPoint.Keys.Team.SeasonId.rawValue) as? String
self.seasonName = representation.valueForKeyPath(EndPoint.Keys.Team.SeasonName.rawValue) as? String
self.teamId = representation.valueForKeyPath(EndPoint.Keys.Team.TeamId.rawValue) as? String
self.teamName = (representation.valueForKeyPath(EndPoint.Keys.Team.TeamName.rawValue) as? String)!
self.rank = representation.valueForKeyPath(EndPoint.Keys.Team.Rank.rawValue) as? String
self.positionId = representation.valueForKeyPath(EndPoint.Keys.Team.PositionId.rawValue) as? String
self.positionName = representation.valueForKeyPath(EndPoint.Keys.Team.PositionName.rawValue) as? String
self.number = representation.valueForKeyPath(EndPoint.Keys.Team.Number.rawValue) as? String
self.birthDate = representation.valueForKeyPath(EndPoint.Keys.Team.BirthDate.rawValue) as? String
self.birthPlace = (representation.valueForKeyPath(EndPoint.Keys.Team.BirthPlace.rawValue) as? String)!
self.citizenship = representation.valueForKeyPath(EndPoint.Keys.Team.Citizenship.rawValue) as? String
self.height = representation.valueForKeyPath(EndPoint.Keys.Team.Height.rawValue) as? String
self.weight = representation.valueForKeyPath(EndPoint.Keys.Team.Weight.rawValue) as? String
self.maritalStatus = representation.valueForKeyPath(EndPoint.Keys.Team.MaritalStatus.rawValue) as? String
self.model = representation.valueForKeyPath(EndPoint.Keys.Team.Model.rawValue) as? String
self.hobby = representation.valueForKeyPath(EndPoint.Keys.Team.Hobby.rawValue) as? String
self.food = representation.valueForKeyPath(EndPoint.Keys.Team.Food.rawValue) as? String
self.book = representation.valueForKeyPath(EndPoint.Keys.Team.Book.rawValue) as? String
self.movie = representation.valueForKeyPath(EndPoint.Keys.Team.Movie.rawValue) as? String
self.wish = representation.valueForKeyPath(EndPoint.Keys.Team.Wish.rawValue) as? String
self.message = representation.valueForKeyPath(EndPoint.Keys.Team.Message.rawValue) as? String
self.biography = representation.valueForKeyPath(EndPoint.Keys.Team.Biography.rawValue) as? String
self.imageURL = representation.valueForKeyPath(EndPoint.Keys.Team.ImageURL.rawValue) as? String
self.teamImageURL = representation.valueForKeyPath(EndPoint.Keys.Team.TeamImageURL.rawValue) as? String
}
#objc static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [TeamItem] {
var teamItemArray: [TeamItem] = []
if let representation = representation as? [[String: AnyObject]] {
for teamItemRepresentation in representation {
if let teamItem = TeamItem(response: response, representation: teamItemRepresentation) {
teamItemArray.append(teamItem)
}
}
}
return teamItemArray
}
}
func ==(lhs: TeamItem, rhs: TeamItem) -> Bool {
return lhs.lastName == rhs.lastName
}
}
EDIT
TeamItem.rank1 means actually that the value of the rank is 1 (the same for others)
This is what've need, hope will help someone:
#objc static func dictionary(#response: NSHTTPURLResponse, representation: AnyObject) -> [String: Array<TeamItem>] {
var teamItemDictionary: [String: Array<TeamItem>] = [:]
if let representation = representation as? [[String: AnyObject]] {
for teamItemRepresentation in representation {
if let teamItem = TeamItem(response: response, representation: teamItemRepresentation) {
if teamItem.rank != nil {
let teamKey = teamItem.teamId! + "-" + teamItem.rank!
if teamItem.teamId != EndPoint.Keys.Team.Type.rawValue {
if let team = teamItemDictionary[teamKey] as [TeamItem]? {
teamItemDictionary[teamKey]?.push(teamItem)
} else {
teamItemDictionary[teamKey] = []
teamItemDictionary[teamKey]?.push(teamItem)
}
}
} else {
if teamItem.teamId != EndPoint.Keys.Team.Type.rawValue {
if let team = teamItemDictionary[teamItem.teamId!] as [TeamItem]? {
teamItemDictionary[teamItem.teamId!]?.push(TeamItem)
} else {
teamItemDictionary[teamItem.teamId!] = []
teamItemDictionary[teamItem.teamId!]?.push(TeamItem)
}
}
}
}
}
}
return teamItemDictionary
}