Swift - read plist file to an array?

ⅰ亾dé卋堺 提交于 2019-12-03 07:31:56

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
      }
    }

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.

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)

    }
}

This will read a resource in your bundle with the name "englishArray.plist" and store it in the immutable variable english. It will be an Optional that you should test before using.

It uses a closure to read the file and return the array, this lets you use a immutable value rather than a mutable variable that can be changed. It's a good idea to use immutables wherever you can - they promote stability.

import Foundation

let english:[String]? = {
  guard let URL = NSBundle
    .mainBundle()
    .URLForResource("englishArray", withExtension: "plist") else {
      return nil
  }
  return NSArray(contentsOfURL: URL) as? [String]
}()

Here is the solution for swift 3. For this solution you do not need to change types in your plist structure (keep Dictionary, Array, as is). Also note that since your array's name in plist is also englishArray so the (value for key) argument in the second if statement is also englishArray.

var myEnglishArray: [String] = []
   if let URL = Bundle.main.url(forResource: "englishArray", withExtension: "plist") {
      guard let englishFromPlist = NSDictionary(contentsOf: URL) else { return [] }
      if let englishArray = englishFromPlist.value(forKey: "englishArray") as? [String] {
         for myEnglish in englishArray {
            myEnglishArray.append(myEnglish)
         }
      }
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!