Viren Patel
Viren Patel

Reputation: 128

iterating through plist file and storing data in array or Dictionary

I am new in swift programing. I'm trying to learn plist file. I have a plist file which has data of Country, State and city. I want to iterate through the data of plist file. But I can't understand how to create an array or dictionary to store the data for country, state and City. Can you help me with how to manipulate the following data of plist file.

    {
Country =     (
            {
        CountryName = India;
        State =             (
                            {
                City =                     (
                    Ahmedabad,
                    Vadodara,
                    Surat,
                    Aanand,
                    Bharuch
                );
                StateName = Gujrat;
            },
                            {
                City =                     (
                    Mumbai,
                    Pune,
                    Nagpur,
                    Nasik,
                    Thane
                );
                StateName = Maharastra;
            },
                            {
                City =                     (
                    Kochi,
                    Kanpur,
                    Alleppey,
                    Thrissur,
                    Thiruvananthapuram
                );
                StateName = Kerala;
            }
        );
            },

Upvotes: 0

Views: 1143

Answers (2)

SHISHIR R AMIN
SHISHIR R AMIN

Reputation: 412

// swift 3 using structure. Manually parsing of data.

struct ListData {
    var countries : [Country]?

    init(dict:[String:AnyObject]) {
        if let countryDict = dict["Country"] as? [[String:AnyObject]] {
            self.countries = parseArray(dictArray: countryDict)
        }
    }

    func parseArray(dictArray:[[String:AnyObject]]) -> [Country] {
        var array = [Country]()
        for dict in dictArray {
            let country = Country(dict: dict)
            array.append(country)
        }
        return array
    }
}
struct Country  {
    var countryName : String?
    var states : [State]?

    init(dict:[String:AnyObject]) {
        countryName = dict["CountryName"] as? String

        if let stateDict = dict["State"] as? [[String:AnyObject]] {
            states = parseArray(dictArray: stateDict)
        }
    }

    func parseArray(dictArray:[[String:AnyObject]]) -> [State] {
        var array = [State]()
        for dict in dictArray {
            let state = State(dict: dict)
            array.append(state)
        }
        return array
    }
}
struct State {
    var stateName : String?
    var cities : [String]?

    init(dict:[String:AnyObject]) {
        self.stateName = dict["StateName"] as? String

        if let cityDict = dict["City"] as? [AnyObject] {
            cities = parseArray(dictArray: cityDict)
        }
    }

    func parseArray(dictArray:[AnyObject]) -> [String] {
        var array = [String]()
        for dict in dictArray {
            array.append(dict as! String)
        }
        return array
    }
}

 var listData : ListData? = nil

 if let path = Bundle.main.path(forResource: "Property List" , ofType: "plist") {
            let rootDict = NSDictionary(contentsOfFile: path) as? [String:AnyObject]
            listData = ListData(dict: rootDict!)
    }

// Using swift 4 and codable protocol.

struct ListData : Codable {
    var countries : [Country]?

    enum CodingKeys : String, CodingKey {
        case countries =  "Country"
    }

}

struct Country : Codable {
    var countryName : String?
    var states : [State]?

    enum CodingKeys : String, CodingKey {
        case countryName =  "CountryName"
        case states = "State"
    }

}

struct State : Codable {
    var stateName : String?
    var cities : [String]?

    enum CodingKeys : String, CodingKey {
        case stateName =  "StateName"
        case cities = "City"
    }

}

var listData : ListData? = nil
if  let url = Bundle.main.url(forResource: "Property List", withExtension: "plist") {
            if let data = try? Data(contentsOf: url) {
                let decoder = PropertyListDecoder()
                do {
                    listData = try decoder.decode(ListData.self, from: data)
                } catch (let err) {
                    print(err.localizedDescription)
                }
            }
        }

Upvotes: 7

Ashwin Shrestha
Ashwin Shrestha

Reputation: 528

You can use Object mapper

https://github.com/Hearst-DD/ObjectMapper

where, install the pod and then create your class as

    class State : Mappable {

      var stateName: String?
      var city: [String]?

      required init?(map: Map) {}

     func mapping(map: Map) {
         stateName <- map["StateName"]
         city <- map["City"]

     }
 }

 class Country : Mappable {
     var countryName: String?
     var state: [State]?

    required init?(map: Map) {}

    func mapping(map: Map) {
        countryName <- map["CountryName"]
        state <- map["State"]

    }

}

class CountryData: Mappable {
    var countries: [Country]?

    required init?(map: Map) {}

    func mapping(map: Map) {
        countries <- map["Country"]

    }
}

get your plist content in a varibale like

 var dictRoot: NSDictionary?
 var countryItems: [String:AnyObject]?
    if let path = Bundle.main.path(forResource: "MyCountryList" , ofType: "plist") {
        dictRoot = NSDictionary(contentsOfFile: path)
    }

    if dictRoot != nil
    {
        // Your dictionary contains an array of dictionary
        // Now pull an Array out of it.
        countryItems  = dictRoot as? [String:AnyObject]
        tableView.reloadData()

    }


let countryData  = CountryData(JSON: countryItems)

now you can use it as you wish

Upvotes: 0

Related Questions