How to read from a plist with Swift 3 iOS app
Asked Answered
H

7

30

-Disclaimer-
I'm extremely new to iOS and Swift development, but I'm not particularly new to programming.

I have a basic iOS application with Swift3 elements in it.
I've created a plist file with some entries I want to read and display in my application. (No write access is necessary)

How can you read a value for a given key for a bundled plist file, in Swift3?

This seems like a really simple question to me, but a bunch of searching is making me question my whole conceptual approach.

Helpful tips would be appreciated.

Histiocyte answered 7/10, 2016 at 6:5 Comment(2)
see this rebeloper.com/read-write-plist-file-swift and this learncoredata.com/plistSpode
The rebeloper site noted above is a link to a library to handle these things. It might be great, I don't know, but it's certainly a long article describing a process that is far more complicated than this process ought to require. The second site is a dead link for me on this day.Donation
C
71

Same way you have done in Swift 2.3 or lower just syntax is changed.

if let path = Bundle.main.path(forResource: "fileName", ofType: "plist") {

    //If your plist contain root as Array
    if let array = NSArray(contentsOfFile: path) as? [[String: Any]] {

    }

    ////If your plist contain root as Dictionary
    if let dic = NSDictionary(contentsOfFile: path) as? [String: Any] {

    }
}

Note: In Swift it is better to use Swift's generic type Array and Dictionary instead of NSArray and NSDictionary.

Edit: Instead of NSArray(contentsOfFile: path) and NSDictionary(contentsOfFile:) we can also use PropertyListSerialization.propertyList(from:) to read data from plist file.

if let fileUrl = Bundle.main.url(forResource: "fileName", withExtension: "plist"),
   let data = try? Data(contentsOf: fileUrl) {
       if let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String: Any]] { // [String: Any] which ever it is 
            print(result)
       }
}
Cherianne answered 7/10, 2016 at 6:9 Comment(3)
Thanks a lot. I found a lot of examples for Swift != 3. I'm concerned about adopting Swift as I've also heard it's had two fairly major redecorations in its very short life.Histiocyte
@Doc It is worth noting that some plists are pre-defined. Most notably, info.plist : static let BASE_URL = Bundle.main.infoDictionary!["MY_BASE_URL"] as! StringMayence
To emphasize the very good point by @Dilapidus, the correct/accepted answer to this question should be based on Bundle.main.infoDictionary ... it's right there waiting for you. No need for more code.Numidia
S
12

As Swift 4 introduces Codable

Step 1: Load the Plist File from bundle.

Step 2: Use PropertyListDecoder for the decoding of property list values into semantic Decodable types.

Step 3: Create Codable Struct

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("toolString is \(settings?.toolString ?? "")")
                print("DeviceDictionary is \(settings?.deviceDictionary?.phone ?? "")")
                print("RootPartArray is \(settings?.RootPartArray ?? [""])")

            } catch {
                print(error)
            }
        }
    }
}
struct MySettings: Codable {
    var toolString: String?
    var deviceDictionary: DeviceDictionary?
    var RootPartArray: [String]?

    private enum CodingKeys: String, CodingKey {
        case toolString = "ToolString"
        case deviceDictionary = "DeviceDictionary"
        case RootPartArray
    }

    struct DeviceDictionary: Codable {
        var phone: String?
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            phone = try values.decodeIfPresent(String.self, forKey: .phone)
        }
    }
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        toolString = try values.decodeIfPresent(String.self, forKey: .toolString)
        deviceDictionary = try values.decodeIfPresent(DeviceDictionary.self, forKey: .deviceDictionary)
        RootPartArray = try values.decodeIfPresent([String].self, forKey: .RootPartArray)

    }
}

Sample Plist file -> https://gist.github.com/janeshsutharios/4b0fb0e3edeff961d3e1f2829eb518db

Schematize answered 12/3, 2018 at 5:2 Comment(2)
I think It has better performance when considered with saving it to NSDictionary or Dictionary right?Merwin
Codable is optimal by AppleSchematize
R
3

Here is example how to get BundleID from Info plist:

var appBundleID = "Unknown Bundle ID"    
if let bundleDict = Bundle.main.infoDictionary, 
   let bundleID = bundleDict[kCFBundleIdentifierKey as String] as? String {
       appBundleID = bundleID
   }

The same way you may easily access any key. This approach is good for many-target projects.

Recollect answered 17/11, 2017 at 15:1 Comment(0)
P
2

Here is a Swift 3 implementation, based on Nirav D's answer:

    /// Read Plist File.
    ///
    /// - Parameter fileURL: file URL.
    /// - Returns: return plist content.
    func ReadPlist(_ fileURL: URL) -> [String: Any]? {
        guard fileURL.pathExtension == FileExtension.plist, let data = try? Data(contentsOf: fileURL) else {
            return nil
        }
        guard let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else {
            return nil
        }
        print(result)
        return result
    }
Pollster answered 8/9, 2017 at 2:3 Comment(2)
Thanks for the new suggestion. Would you please walk me through how this is different from Nirav D's answer? I like that you have exception handling involved. Is that basically it?Histiocyte
@JamesTSnell Thank you for your question. The two answers are basically the same.I just abstracted his answer as a function for calling easily. Nirav D's answer didn't handle the exception or something wrong. So in my function, if some bad things happened will return nil. Hope for help.Pollster
B
0

For Swift 3.0, Following code directly targeting to key. Where as dict object will give everything which will be there in your plist file.

if let path = Bundle.main.path(forResource: "YourPlistFile", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
            let value = dict["KeyInYourPlistFile"] as! String
    }
Brickwork answered 30/10, 2017 at 6:9 Comment(0)
I
0

In AppDelegate File

var bundlePath:String!
    var documentPath:String!
    var plistDocumentPath:URL!
    let fileManager = FileManager()


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
    {
        bundlePath = Bundle.main.path(forResource: "Team", ofType: "plist")

        documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first

        plistDocumentPath = URL.init(string: documentPath)?.appendingPathComponent("Team.plist")
        print(plistDocumentPath.path)

        if !fileManager.fileExists(atPath: plistDocumentPath.path){

            do {
                try fileManager.copyItem(atPath: bundlePath, toPath: plistDocumentPath.path)
            } catch  {
                print("error Occured \(error.localizedDescription)")
            }

        }


        return true
    }

In ViewController

 @IBOutlet weak var TeamTable: UITableView!
    var appDelegate:AppDelegate!
    var arrayForContacts:[[String:Any]]! // array object


    override func viewDidLoad() {
        super.viewDidLoad()




        appDelegate = UIApplication.shared.delegate as! AppDelegate


    }
    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        if appDelegate.fileManager.fileExists(atPath: appDelegate.plistDocumentPath.path){
            arrayForContacts = []
            if let contentOfPlist = NSArray.init(contentsOfFile: appDelegate.plistDocumentPath.path ){
                arrayForContacts = contentOfPlist as! [[String:Any]]
                TeamTable.reloadData()
            }

        }
    }
Isom answered 2/11, 2017 at 4:53 Comment(0)
H
0

You can also read value directly from your plist file by simply

let value = Bundle.init(for: AppDelegate.self).infoDictionary?["your plist key name"] as? Any
Hambletonian answered 12/2, 2018 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.