Swift 2 iOS 9: Plist Reading and Writing

2019-06-24 07:05发布

问题:

I believe something has changed within Swift 2, because no tutorials on how to read and write to property lists seem to be working.

Can anyone whose developing for iOS 9 share their method of R/W to Plists using Swift 2 on Xcode 7?

回答1:

This is working for me on iOS 9 and Xcode 7:

let filePath = NSBundle.mainBundle().pathForResource("FileName", ofType: "plist")!    
let stylesheet = NSDictionary(contentsOfFile:filePath)

The only thing is that the result is NSDictionary and not Dictionary.



回答2:

Hopefully this is helpful - without code it is difficult to answer.

The change that tripped me up is that when copying a plist file over to the documents directory the method stringByAppendingPathComponent is no longer available. You have to use NSURL instead.

If you have a preparePlistForUseMethod it should now look like this.

let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
        let url = NSURL(string: rootPath)
        plistPathInDocument = (url?.URLByAppendingPathComponent("plistfilename.plst").absoluteString)!

if !NSFileManager.defaultManager().fileExistsAtPath(plistPathInDocument){
            let plistPathInBundle = NSBundle.mainBundle().pathForResource("plistfilename.plst", ofType: "plist")!

            do{
            try NSFileManager.defaultManager().copyItemAtPath(plistPathInBundle, toPath: plistPathInDocument)
                print("plist copied")
            }
            catch{
                print("error copying plist!")
            }
        }
        else{
            print("plst exists \(plistPathInDocument)")
    }
}


回答3:

For reading on a PLIST, I encapsulated the logic in a Singleton. In my case, I want to read the file URLs.plist.

class URLs {

    class var sharedInstance: URLs {
        struct Singleton {
            static let instance = URLs()
        }
        return Singleton.instance
    }

    private var urls: NSDictionary!

    required init() {
        let filePath = NSBundle.mainBundle().pathForResource("URLs", ofType: "plist")!
        self.urls = NSDictionary(contentsOfFile:filePath)
    }

    var backendBaseUrl: String {
        get {
            return urls["BackendBaseUrl"] as! String
        }
    }

    var locationEndpoint: String {
        get {
            return urls["LocationEndpoint"] as! String
        }
    }

}

Wherever you need to access one of those URLs, you just:

URLs.sharedInstance.backendBaseUrl

This works fine with Xcode 7.1 and Swift 2.1.