Search code examples
swiftproperty-list

Check for Property List


I'm currently learning Swift 2 on XCode 7 and trying to figure out how to test if a property list is available to read from.

I have a convenience initializer that works but I want to implement a test to see if the propertyList exists, otherwise just create an empty array.

Here's my code far:

Property List creation and write

let propertyList: NSArray = photoGrid.photos.map { $0.propertyListRepresentation() }

let path = NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, 
    .UserDomainMask, 
    true)[0] as NSString

let file = path.stringByAppendingPathComponent("data.plist")

propertyList.writeToFile(file, atomically: true)

Convenience Init

convenience init(propertyList: NSArray) {
    self.init()

    // test if property list exists {
    self.photos = propertyList.map { (param: AnyObject) -> Photo in
        let pl = param as! NSDictionary
        let photo = Photo(propertyList: pl)
        return photo!
    }
    // } else {
    //    print("Property List does not exist... Created empty object array)
}

Solution

  • First of all use the URL related API to get the file URL

    let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
    let fileURL = documentDirectoryURL.URLByAppendingPathComponent("data.plist")
    

    Second of all, there is a class NSPropertyListSerialization which is preferable to the implicit property list serialization of NSArray.

    Third of all, in Swift use native collection types rather than the type-unspecified Foundation classes.

    This is an init method which creates the file URL, checks file exists and assigns the mapped Photo instances or an empty Photo array to the instance variable.

    init() {
      let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
      let fileURL = documentDirectoryURL.URLByAppendingPathComponent("data.plist")
      if let data = NSData(contentsOfURL:fileURL), propertyList = try! NSPropertyListSerialization.propertyListWithData(data, options: [], format: nil) as? [[String:AnyObject]] {
        self.photos = propertyList.map { Photo(propertyList: $0)! }
      } else {
        self.photos = [Photo]()
      }
    }
    

    The two try! expressions are safe because the document directory exists and the property list file has a predictable format.