Swift: Using stringWithContentsOfURL

Discussion in 'Mac Programming' started by Perkin, Jun 5, 2014.

  1. Perkin, Jun 5, 2014
    Last edited: Jun 5, 2014

    Perkin macrumors newbie

    Joined:
    Oct 22, 2013
    #1
    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.
     
  2. si31 macrumors newbie

    Joined:
    Jul 27, 2014
    #2
    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..
     
  3. Perkin thread starter macrumors newbie

    Joined:
    Oct 22, 2013
    #3
    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?
     

Share This Page