Harsh Chitrala
Harsh Chitrala

Reputation: 67

Read Write array data to plist not working

func readWriteData(){

        let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
        let cachePath = paths.first
        //        let bundleName = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String
        let filePath = NSURL(fileURLWithPath: cachePath!).URLByAppendingPathComponent("cachedProducts.plist").path
        var isDir : ObjCBool = false
        var error: NSError?
        if NSFileManager.defaultManager().fileExistsAtPath(filePath!, isDirectory: &isDir) {
            var plistArray = NSArray(contentsOfFile: filePath!)
            print(plistArray)//retrieving stored data


        }else {
            do {
                try NSFileManager.defaultManager().createDirectoryAtPath(filePath!, withIntermediateDirectories: false, attributes: nil)
                var cachedArray = [AnyObject]()
                cachedArray.append("Harsh")
                let cachedProductarray : NSArray = cachedArray
                cachedProductarray.writeToFile(filePath!, atomically: true)
                //Storing data to plist


            } catch let error as NSError {
                NSLog("\(error.localizedDescription)")
            }
        }
}

when i try to print plistArray it's returning nil. Please help me with the solution. I tried this using cachesDirectory and Document Directory it's the same scenario with both

Upvotes: 1

Views: 66

Answers (1)

vadian
vadian

Reputation: 285079

The cache directory is supposed to be created at cachePath, not at filePath.

Rather than using the quite primitive writeToFile method of NSArray I'd recommend to use NSPropertyListSerialization in conjunction with NSData's writeToFile:options:error (still better writeToURL...) method to get meaningful error messages.

Upvotes: 1

Related Questions