3

I am writing UI tests for iOS application. I want to read data from a local json file.

I am using the following code to get the path for my json file:

func testExample() {

    readJSON()
}

func readJSON(){
    let bundle = Bundle(for:myTestClass.self)
    if let path = bundle.url(forResource: "myurl", withExtension: "json"){
        print("Got the path")
        print(path)
    }
    else{
        print("Invalid filename/path")
    }

I have tried using the solution for the following stackoverflow question : Reading in a JSON File Using Swift. Didn't work!

Also, I had a look at the following Apple documentation: https://developer.apple.com/swift/blog/?id=37

Any help would be greatly appreciated!

1
  • is your json stored in local directory or is it attached to Xcode?
    – KrishnaCA
    Feb 18, 2017 at 5:47

3 Answers 3

10

First of all, you need to check the .json file is in the same target with the test file. If the file is in the main target, you have to use Bundle.main. However if it is in the same target with your test, use the below code.

let t = type(of: self)
let bundle = Bundle(for: t.self)
let path = bundle.path(forResource: "myurl", ofType: "json")
0

That's not how you read local json files from Bundle in iOS. It's done in the following way:

// "myUrl" is assumed to be your json file name 

if let pathStr: String = Bundle.main.path(forResource: "myurl", ofType: ".json") {
    print("json path: \(pathStr)")
}
4
  • That is exactly how we read local json file in the UI Test Bundle. Feb 19, 2017 at 23:55
  • @KushalJogi, what's the problem? Does it not work? May I please know
    – KrishnaCA
    Feb 20, 2017 at 5:40
  • This will not work because main bundle is not the one you think it is, it is test runner's bundle and i'm guessing you do not have that json there
    – Julian
    Jan 26, 2018 at 11:43
  • @JulianKról, Thanks for the info. Please write it as an answer below with sample code if possible.
    – KrishnaCA
    Jan 26, 2018 at 11:48
0

I just found resources added to XCUITest targets will be placed under Bundle.main.resourcePath + "/PlugIns/<TARGET_NAME>.xctest/". However, I'm not sure if there were better ways to access them rather than hard-coding the sub-directory path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.