Async-
Async-

Reputation: 3289

URLForResource() returns always nil, swift 2.3, iOS10

I am trying to test something, and need access to the file which is in the same directory as the test class (in fact in sub-directory). I am trying to do it like this:

let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics", subdirectory: "Calendars")

I also tried it like this:

let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics")

My class is called ParserTest. The file I am trying to access is located as shown: enter image description here

I tried to get the file path:

 if let filePath = NSBundle.mainBundle().pathForResource("MasterCalendar", ofType: "ics", inDirectory: "Calendars") {
        print("PATH: ", filePath)
    }

I tried to remove inDirectory, and put also "CallInTests/Calendar". Nothing worked. The file itself is added in the Target for tests:

enter image description here

AND for the project: enter image description here

Regardless of what I do, the fileURL returns always nil.

Upvotes: 2

Views: 139

Answers (2)

pbodsk
pbodsk

Reputation: 6876

It is not quite clear to me how your testBundle is defined, but this works for me:

let bundle = Bundle(for: YourClassHere.self)

So in your case that would be:

let bundle = Bundle(for: ParserTest.self)

Which you can then use like so:

if let path = bundle.path(forResource: "MasterCalendar", ofType: "ics") {
  //magic goes here
}

Swift 2.3 version

let bundle = NSBundle(forClass: ParserTest.self)

if let path = bundle.pathForResource("MasterCalendar", ofType: "ics") {
   //magic still goes here :)
}

Hope that helps you.

Upvotes: 1

Tushar
Tushar

Reputation: 3052

try the following way :

let testBundle = NSBundle(forClass: self.dynamicType)
let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics")
XCTAssertNotNil(fileURL)

Upvotes: 0

Related Questions