getting data from an array based on cell for item

2019-09-01 05:35发布

问题:

I have an array of dictionaries like

var array = [["name":abc,"number":123,"address":xyz],["name":def,"number":456,"address":yzx],["name":ghi,"number":789,"address":ooo],["name":jkl,"number":012,"address":ppp]]

Data coming from server

I want to display this data in a collectionview, based on cell for item index. Can anyone help me to do this?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HistoryCollectionViewCell
    var dict = pro[indexpath]
    cell.nameobj.text = dict["name"] as! String
    cell.addressobj.text = dict["address"] as! String
    return cell    
}

回答1:

1) Create a person class

class Person : NSObject {

    var name = ""
    var number = ""
    var address = ""

    static let sharedInstance: PersonModel = PersonModel()


    func getPersonModel(_ dictionary:NSDictionary) -> Person{
        let person = Person()
        person.name = dictionary.object(forKey: "name") as! String
        person.number = dictionary.object(forKey: "number") as! String
        person.address =  dictionary.object(forKey: "address") as! String
        return person
    }
}

2) Map your json to person object model in the respective viewController the next point return the parsed json which can be used in here .

let personDict = convertStringToDictionary(text: "Json obtained from server")
let personArray = personDict.object(forKey: "Person") as! NSArray
for person in PesronArray {
    let personModel = PersonModel.sharedInstance.getPersonModel(personDict as! NSDictionary)
    persons.add(personModel)
}

3) You can use this method or create your own extension to parse the json into dictionary.

func convertStringToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil

    }

4) You can populate the collection view Using the persons array form the step 2.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
        let personObject = persons.object(at: indexPath.row) as? Person
}

Note : This code has not been tested, the json parser and conversion may vary with respect to JSON received from server.



标签: ios swift4