Swift – Unable to read/write from file

I’m actually not sure whether I’m not able to read or unable to write. I’m pretty sure writing works. I’m using Swift.

Here are my project files.

  • How to delete expired provisioning profiles in Xcode 8.3
  • Color difference between drawRect and Interface Builder?
  • tableView reloadData not working
  • CoreData and RestKit performance while importing very large datasets
  • Xcode iOS 8 Keyboard types not supported
  • XCode: Displaying a UIDatePicker when user clicks on UITextbox
  • I’m trying to write an array of arrays to a file, and then read that array of arrays when the app launches. Here’s my code for writing and reading, respectively. listOfTasks is my array of arrays variable.

    Writing:

    let cocoaArray : NSArray = listOfTasks
    cocoaArray.writeToFile(String(fileURL), atomically: true)
    

    Reading:

    listOfTasks = NSArray(contentsOfFile: String(fileURL)) as! [Array<String>]
    

    fileURL:

    let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last
    
    let fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")
    

    I’m happy to provide additional information as necessary. Thanks in advance!

    Solutions Collect From Internet About “Swift – Unable to read/write from file”

    Not sure where’s exactly your problem, but here’s a full working Playground sample:

    let fileUrl = NSURL(fileURLWithPath: "/tmp/foo.plist") // Your path here
    let array = [["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], ["One", "Two", "Three"]] // Your array of arrays here
    
    // Save to file
    (array as NSArray).writeToURL(fileUrl, atomically: true)
    
    // Read from file
    let savedArray = NSArray(contentsOfURL: fileUrl) as! [[String]]
    
    print(savedArray)