1

I'm looking for the best way (or easiest) to import data into my iOS app using Swift. I've got a file containing recipes and I have to read in the recipe names and instructions. Example:

Fudge brownies

  1. Mix ingredients in processors until consistent.
  2. Prepare baking sheet with coconut oil and set over at 425. ....

So I have to import several dozen recipes, my questions are

Would it be best to read in a text file?

If so how is this done in Swift?

Also how do I avoid issues with reading the title and recipe into separate variables?

Kampai
  • 22,848
  • 21
  • 95
  • 95
Mohammed B
  • 305
  • 1
  • 4
  • 14

2 Answers2

2

You can read in a text file quite easily doing something like this:

let path = NSBundle.mainBundle().pathForResource("fileName", ofType: "txt")
var dataString = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)

Note you'll have to import Foundation.

You could then create a method to parse the dataString, something like

func parseDataString(string: String)

which you could send the dataString to.

You could put markers (e.g. special characters like (*) ) in the text file that would allow this method to figure out where the titles end and the directions start. There are a number of ways it could be done.

You could then persist your data using CoreData.

trevorj
  • 2,029
  • 1
  • 16
  • 11
0

I would strongly suggest using JSON data in the files. JSON is a very simple markup format that gives structure to text files, and lets you basically say things like title=BBQ ribs. The reason you use JSON is that Cocoa has really good JSON handling built right in. Check out this thread, it probably does exactly what you want...

How do I parse JSON with Objective-C?

Community
  • 1
  • 1
Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98