Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read from and write to files using Swift on a mac?

I've been looking all over the Internet for an answer to this one, and every answer I've gotten either hasn't worked, is enormously complex, is for iOS only, or a combination of the three. I am just looking for a simple way to perform file I/O in Swift for use on a Mac. So I guess that a way to mix c++ and swift would also work, but for that I've had the same problems as before. Any help would be greatly appreciated!

like image 926
Stephen Brimhall Avatar asked Aug 12 '14 23:08

Stephen Brimhall


People also ask

How do I create and write to a file in Swift?

To create a text file in Swift, call createFile() function on the file manager object, and pass the file path and contents to the function.

How to read from text file in Swift?

To read a Text File in Swift, we can prepare the file url and then use String initializer init(contentsOf: url) that returns file content as a string.

How do I use text files in Xcode?

To add a text file to the project, right-click on the project folder in the project view in the left pane and select the option New Item... In the dialog that appears, select the Other category and the Empty file option. Name the file numbers. txt.


2 Answers

Abhi Beckert's code updated to Swift 3:

import Cocoa

var str = "Hello, playground"

// get URL to the the documents directory in the sandbox
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL

// add a filename
let fileUrl = documentsUrl.appendingPathComponent("foo.txt")

// write to it
try! str.write(to: fileUrl!, atomically: true, encoding: String.Encoding.utf8)
like image 200
teacup Avatar answered Sep 17 '22 17:09

teacup


There are many options, it depends what you're trying to write and also the size/etc of the data (hundreds of megabytes of data requires different techniques).

But the simplest method is:

import Cocoa

var str = "Hello, playground"

// get URL to the the documents directory in the sandbox
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL

// add a filename
let fileUrl = documentsUrl.URLByAppendingPathComponent("foo.txt")

// write to it
str.writeToURL(fileUrl, atomically: true, encoding: NSUTF8StringEncoding, error: nil)

One thing that might be catching you out is OS X has strict sandboxing to prevent which parts of the disk you can write to. As a security measure for users pasting random code into Xcode and to prevent bugs erasing somebody's entire hard drive... the Playground enforces the sandbox although many mac apps do not use sandboxing (it's usually only enabled for apps deployed in Apple's store).

Your app has a sandbox on the disk that you can write to, this is what NSFileManager() is returning URL for above.

To punch a hole in the sandbox to the rest of the disk, you need to involve the user. Eg if they drag a file onto your app icon, you can write to it. If they select a file in an open or save panel then you can write to that. If the user selects a directory, or even the root of the file system, you can write to the all descendants of the selection.

It's also possible to persist access to a file/directory across app launches, although I've never looked into how that works. NSDocumentController does it for you, if you use that for a document based app.

like image 35
Abhi Beckert Avatar answered Sep 19 '22 17:09

Abhi Beckert