Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Perkin

macrumors newbie
Original poster
Oct 22, 2013
16
0
EDIT: SOLVED

I trying to learn Swift, but just can't seem to get my head around the variation on the syntax.
In my project bundle I've included a file called 'index.text'
In Obj-C I would get it's contents with
Code:
NSString indexContent = [NSString stringWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"text"]] encoding:NSUTF8StringEncoding error:NULL ]];

So ... How do I now do this in Swift?

I found that the index.text wasn't been copied into the build app, so the file was always coming up nil - once that was corrected the file was then read properly.

I also changed the way it's read in...
Code:
        let path = NSBundle.mainBundle().pathForResource("index", ofType: "text")
        var possibleContent = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)
        
        if let text = possibleContent {
            println(text)
        }

So I had it correct from the start, just a different default project build phases setting caused the file not to be included.
 
Last edited:
Hello how did you get it to be added to the bundle. I have the same problem: I get an error saying it returns nil. It is saying it is being copied to the bundle in the build phases though..
 
I can't remember exactly as it's been a while, but, I added the file in the project settings somewhere. May have been in Build Settings or Build Phases?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.