Swift 2 iOS 9: Reading and Writing Plist

I suppose something has changed in Swift 2, because no tutorial on how to read and write to property lists seems to work.

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

+4
source share
3 answers

This works for me on iOS 9 and Xcode 7:

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

The only result is an NSDictionary , not a Dictionary .

+2
source

Hope this is helpful - without code it's hard to answer.

The change that spurred me on is that when copying the plist file to the document directory, the stringByAppendingPathComponent method is no longer available. You should use NSURL instead.

If you have a preparePlistForUseMethod method, it should 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)") } } 
+1
source

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

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

If you need access to one of these URLs, you simply:

 URLs.sharedInstance.backendBaseUrl 

This works great with Xcode 7.1 and Swift 2.1.

+1
source

All Articles