Reputation: 59
I am trying to get a particular logged in ID's data in profile but I am unable to get it I have viewed many links but its not working for me. Below is my function that I have used to get data
Function
func getCompanyFunc() {
let empURL = URL(string: "http://172.16.1.22/Get-Company-API/get-companies/")
URLSession.shared.dataTask(with: empURL!) { (data, response, error) in
do {
if error == nil {
self.getCompanyArray = try JSONDecoder().decode([CompanyDataProfile].self, from: data!)
for mainArr in self.getCompanyArray {
DispatchQueue.main.async {
let companyDefaultValue = UserDefaults.standard
if let userID = companyDefaultValue.string(forKey: "user_type_id") {
self.getComData = self.getCompanyArray.filter { $0.company_id == userID }
print("Company ID Profile=\(userID)")
self.companyName_lbl.text = mainArr.company_name
}
}
}
print("****Employee Data****\(self.getCompanyArray)")
}
}
catch {
print("Error in get JSON Data Employee\(error)")
}
}.resume()
}
Upvotes: 0
Views: 202
Reputation: 4552
Try this.
UserListObject
import UIKit
class UserListObject: NSObject {
var strCompanyID: String = ""
var strFirstName: String = ""
var strLastName: String = ""
var strEmail: String = ""
class func parseFromDictionary(dict: NSDictionary) -> UserListObject {
let objUser = UserListObject()
if let company_id = dict["company_id"] as? String {
objUser.strCompanyID = company_id
}
if let fname = dict["fname"] as? String {
objUser.strFirstName = fname
}
if let lname = dict["lname"] as? String {
objUser.strLastName = lname
}
if let email_id = dict["email_id"] as? String {
objUser.strEmail = email_id
}
return objUser
}
}
Your ViewController
Define this globally : var arrUsers = [UserListObject]()
so once you get data from API you can store it like below.
APIsManager.postCall(url!, params: _parameters, success: { (response) in
//CommonHelper.hideProgress()
let JSONData = response as! NSDictionary
if(JSONData.object(forKey: "Success") as! Bool == true) {
self.arrUsers.removeAll()
let arrData = JSONData.value(forKey: "Data") as! NSArray
for i in 0..<arrData.count {
let dict = arrData.object(at: i) as! NSDictionary
let objUser = UserListObject.parseFromDictionary(dict: dict)
self.arrUsers.append(objUser)
}
}
else {
// Error
}
}) { (response) in
//Error
}
Once you get All users in arrUsers than you need to filter like Below.
let objLoggedInUser = self.arrUsers.filter{ $0. strCompanyID == YOUR_USERDEFAULT_ID}.first // THAT WILL RETURN YOU WHOLE OBJECT WITH ALL DETAILS
Now you can get values like.
self.lblFirstName.text = objLoggedInUser. strFirstName
self.lblLastName.text = objLoggedInUser. strLastName
Upvotes: 1