Im trying to read a text file using a Swift playground with the following
let dirs : String[]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? String[] if (dirs != nil) { let directories:String[] = dirs!; let dir = directories[0]; //documents directory let path = dir.stringByAppendingPathComponent(file); //read let content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil) }
However this fails with no error. It seems the first line stops the playground from outputting anything below
playground file. Open Utility inspector, In the playground press opt-cmd-1 to open the File Inspector. You should see the playground on the right. If you don't have it selected, press cmd-1 to open the Project Navigator and click on the playground file.
An Xcode project allows you to create real apps that you could eventually upload to the App Store (providing you became an Apple Developer). An Xcode Playground allows you to play with code and test it out. It isn't for mainstream developing.
You can also put your file into your playground's resources. To do this: show Project Navigator with CMD + 1
. Drag and drop your file into the resources folder. Then read the file:
On XCode 6.4 and Swift 1.2:
var error: NSError? let fileURL = NSBundle.mainBundle().URLForResource("Input", withExtension: "txt") let content = String(contentsOfURL: fileURL!, encoding: NSUTF8StringEncoding, error: &error)
On XCode 7 and Swift 2:
let fileURL = NSBundle.mainBundle().URLForResource("Input", withExtension: "txt") let content = try String(contentsOfURL: fileURL!, encoding: NSUTF8StringEncoding)
On XCode 8 and Swift 3:
let fileURL = Bundle.main.url(forResource: "Input", withExtension: "txt") let content = try String(contentsOf: fileURL!, encoding: String.Encoding.utf8)
If the file has binary data, you can use NSData(contentsOfURL: fileURL!)
or Data(contentsOf: fileURL!)
(for Swift 3).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With