Swift - read plist file to an array?

16,515

Solution 1

Change your root object to Array, then

var myEnglishArray: [String] = []
if let URL = NSBundle.mainBundle().URLForResource("englishArray", withExtension: "plist") {
      if let englishFromPlist = NSArray(contentsOfURL: URL) as? [String] {
        myEnglishArray = englishFromPlist
      }
    }

Solution 2

Swift 4

The absolute simplest way to do this is

    let url = Bundle.main.url(forResource: "Sounds", withExtension: "plist")!
    let soundsData = try! Data(contentsOf: url)
    let myPlist = try! PropertyListSerialization.propertyList(from: soundsData, options: [], format: nil)

The object myPlist is an Array or Dictionary, whichever you used as the base of your plist.

Solution 3

Swift 4

You can use Codable which is pure swift type.

Firstly load Plist file from bundle then use PropertyListDecoder

Complete code -

    func setData() {
        // location of plist file
        if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {

            do {
                var settings: MySettings?
                let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
                    let decoder = PropertyListDecoder()
                settings = try decoder.decode(MySettings.self, from: data)
                print("array  is \(settings?.englishArray ?? [""])")//prints array  is ["Good morning", "Good afternoon"]


            } catch {
                print(error)
            }
        }
    }
}
struct MySettings: Codable {

    var englishArray: [String]?

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        englishArray = try values.decodeIfPresent([String].self, forKey: .englishArray)

    }
}
Share:
16,515
Miguel
Author by

Miguel

Updated on June 05, 2022

Comments

  • Miguel
    Miguel almost 2 years

    I have created a mini translation from English words to Spanish words. I would like to use the englishArray.plist instead of my englishArray = ["the cat"] How can I create this?

    enter image description here

    I have also used a localizable.strings to retrieve the value "the cat" for "el gato" but I would like to retrieve this from englishArray.plist

    I started off with this but not sure if I'm on the right path

    let path = NSBundle.mainBundle().pathForResource("englishArray", ofType: "plist") 
    let plistEnglishArray = NSArray(contentsOfFile: path!)
    

    Here is the rest of my code:

    var englishArray: [String] = ["rainbow", "boots", "heart", "leaf", "umbrella", "tired", "angry", "cry", "the cat" ]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        self.translateTextField.delegate = self
        picker.delegate = self
        picker.dataSource = self
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func translateButtonTapped(sender: UIButton) {
    
        let emptyString = self.translateTextField.text
    
        if (emptyString!.isEmpty) {
    
            print("please enter a word")
    
        }
    
        for transIndex in englishArray.indices {
            if englishArray[transIndex] == emptyString!.lowercaseString {
    
                //englishArray
    
                //translateLabel.text = "\(spanishArray[transIndex])"
                translateLabel.text = NSLocalizedString(emptyString!.lowercaseString, comment:"")
    
    
                print(emptyString)
                return
    
            }
        }
    }
    
  • Leo Dabus
    Leo Dabus about 8 years
    why don't you just cast your NSArray using conditional cast if let englishArray = NSArray(contentsOfURL: url) as? [String] {
  • Leo Dabus
    Leo Dabus about 8 years
    you don't need an extra array and/or append if let url = NSBundle.mainBundle().URLForResource("englishArray", withExtension: "plist"), englishArray = NSArray(contentsOfURL: url) as? [String] { for word in englishArray { print(word) } }
  • Miguel
    Miguel about 8 years
    is this code placed in viewDidLoad() right? @khuong291
  • Leo Dabus
    Leo Dabus about 8 years
    If you need to convert your array to data you can use keyed archiver
  • Sulthan
    Sulthan about 8 years
    I am not really sure why you are converting a [String] array into another [String]. Why not just myEnglishArray = englishFromPlist instead for-in?
  • Pontus Ivarsson
    Pontus Ivarsson almost 5 years
    assuming you have this code inside viewDidLoad(), how do you then share the myPlist variable to other files?