HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

CSV2Plist

Convert a comma-separated values (CSV) file into a property list (Plist) file.

Code

import UIKit

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()

        // read  - desktop - Users/user/Desktop/File.csv
        // write - desktop - Users/user/Desktop/File.plist
        let readString = "Users/user/Desktop/File.csv"
        let writeString = "Users/user/Desktop/File.plist"

        // read  - main bundle        - File.csv
        // write - document directory - Users/user/Library/Developer/CoreSimulator/Devices/########-####-####-####-############/data/Containers/Data/Application/########-####-####-####-############/Documents/File.plist
        //let readString = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("File.csv")
        //let writeString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0].stringByAppendingPathComponent("File.plist")

        let rowCharacterSet = NSCharacterSet(charactersInString: "\n")
        let columnCharacterSet = NSCharacterSet(charactersInString: ",")

        let fileString = NSString(contentsOfFile: readString, encoding: NSUTF8StringEncoding, error: nil)
        let fileScanner = NSScanner(string: fileString!)
        let fileArray = NSMutableArray()

        while (!fileScanner.atEnd)
        {
            var rowString: NSString?

            fileScanner.scanUpToCharactersFromSet(rowCharacterSet, intoString: &rowString)

            let rowScanner = NSScanner(string: rowString!)
            let rowArray = NSMutableArray()

            while (!rowScanner.atEnd)
            {
                var columnString: NSString?

                rowScanner.scanUpToCharactersFromSet(columnCharacterSet, intoString: &columnString)
                rowScanner.scanCharactersFromSet(columnCharacterSet, intoString: nil)

                rowArray.addObject(columnString!)
            }

            fileArray.addObject(rowArray)
        }

        fileArray.writeToFile(writeString, atomically: true)
    }
}