Last active
April 19, 2017 15:01
-
-
Save YonathanMeguira/916fc948c55edc19547e943a5055146a to your computer and use it in GitHub Desktop.
AlamoFire casting Dictionary to Struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//casting result from alamofire API Call to struct | |
struct dataStruct { | |
var address = String() | |
var age = Int() | |
var balance = String() | |
var company = String() | |
var email = String() | |
var gender = String() | |
var name = String() | |
var phone = String() | |
var picture = String() | |
} | |
@IBOutlet weak var dataTable: UITableView! | |
var data = [dataStruct]() | |
func loadData() { | |
Alamofire.request("https://api.myjson.com/bins/62za3").responseJSON { response in | |
if let result = response.result.value { | |
let arr = result as! Array<Any> | |
for item in arr { | |
let obj = item as! NSDictionary | |
let toAppend = dataStruct(address: obj["address"] as! String, age: obj["age"] as! Int, balance: obj["balance"] as! String, company: obj["company"] as! String, email: obj["email"] as! String, gender: obj["gender"] as! String, name: obj["name"] as! String, phone: obj["phone"] as! String, picture: obj["picture"] as! String) | |
self.data.append(toAppend) | |
} | |
} | |
print(self.data) | |
self.dataTable.reloadData() | |
} | |
//then to display the result in the table veiw row | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
loadData() | |
dataTable.dataSource = self | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ | |
return data.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell | |
{ | |
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) | |
cell.textLabel?.text = data[indexPath.row].name | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment