brimstone
brimstone

Reputation: 3400

Swift write to file (iOS)

How can I write to an xml document in Swift? I have this code:

let content = "<tag>Example</tag>"
var error: NSError?
content.writeToFile(NSBundle.mainBundle().pathForResource("my_file", ofType: "xml")!, atomically: true, encoding: NSUTF8StringEncoding, error: &error)

But this does not update the file in my Xcode project or on the device. How can I get this to work?

Upvotes: 1

Views: 3909

Answers (1)

Duncan C
Duncan C

Reputation: 131491

To collect all the fragments provided in comments into one place:

The app bundle is read-only on iOS. You can't save to it. It isn't forced to be read-only on Mac OS, but you should still treat it as such. As a result of this difference, code that modifies the app bundle may work on the simulator, but fail on an actual device.

You should save your contents to a file in the user's documents directory or one of the other sandbox directories. That code might look like this:

let docsPath = NSSearchPathForDirectoriesInDomains( 
  NSSearchPathDirectory.DocumentDirectory,
  NSSearchPathDomainMask.UserDomainMask,
  true)[0] as! NSString
let filePath = docsPath.stringByAppendingPathComponent("myfile")
let content = "<tag>Example</tag>"
var error: NSError?
content.writeToFile(filePath, 
  ofType: "xml", 
  atomically: true, 
  encoding: NSUTF8StringEncoding, 
  error: &error)

Then you should add error-checking that checks the bool result of the writeToFile command. If the result is false, check the error to see what went wrong.

Note that there is built-in support in iOS for reading XML, and quite a few third party libraries for saving collections of objects in XML format. You should take a look at NSXMLParser for reading. I can't really recommend one of the XML writing libraries over the others.

If you aren't wedded to XML, you might take a look at JSON. It's more compact, easier to write, easier to read, less memory-intensive, and there is built-in system support for both reading and writing Cocoa data structures from/to JSON files.

Upvotes: 3

Related Questions