Reputation: 8995
Ok, Managed to put this code together, created a plist file with Xcode which I copied {using iTunes} to the app folder, it doesn't work...
import Foundation
class getBeaconConfiguration {
var myBeaconsDict: NSDictionary?
func getBeacons() {
let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
let sourcePath:NSString = documentsPath.stringByAppendingString("/beacons.plist")
let dict = NSDictionary(contentsOfFile: sourcePath as String)
print("dict",dict)
}
}
The path is good, and the plist is there, but the NSDictionary returned is a null pointer it seems. How do you do this in swift 2.0.
Upvotes: 0
Views: 1233
Reputation: 7252
A little different in Swift 2.0, String no longer has stringByAppendingPathComponent, and you should be using this method when working with file paths.
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let sourcePath = documentsPath.stringByAppendingPathComponent("beacons.plist")
let dictionary = NSDictionary(contentsOfFile: sourcePath as String)
print("dict: \(dictionary)")
Upvotes: 1
Reputation: 150625
Get Create a URL to the file and then create a dictionary from it.
let filename = "beacons.plist"
guard
let fileURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent(filename)
else { fatalError("Unable to get file") }
let dict = NSDictionary(contentsOfURL: fileURL)
Upvotes: 1