1

I am trying to read a plist file present in Xcode bundle,

Approach #1 (Didn't work): I was using a static variable(Line #23 in below screenshot) which returns the path of file present in bundle, It didn't work Nonworking1

Approach #2 (Didn't work): Using Bundle.main to read a file didn't work Notworking2

Approach #3 (Working solution): When I write a function (Line #30 in below screenshot) with same lines of code, It works! working

Initially I was trying to read file using the static variable and wasted 2 days, until I figured out that using function instead of static variable would work.

Questions:

  1. I cant find any relevant documentation, Can anyone explain why this Approach #1 didn't work?
  2. Is the type(of:) specific for object type not class type?
Saif
  • 2,678
  • 2
  • 22
  • 38

1 Answers1

1

The correct way to read file from within UITest target is

Correct way to read file:

func getPath() -> String?  {
    let bundle = Bundle(for: type(of: self))
    let path = bundle.path(forResource: "MockMDM", ofType: "plist")
    return path
}

Also let me share the code which seem correct but wont work

Wrong way to read file:

static var mockMDMFile: [String: Any]? {
    
    if let path = Bundle.main.path(forResource: "MockMDM", ofType: "plist") {
        let mdmDict = NSDictionary(contentsOfFile: path) as! [String: Any]
        return mdmDict
    }
    return nil
}

Reason for failure of wrong way:

  • App has multiple bundles, and the files present in the UITest target will be part of a different bundle NOT Main bundle (Bundle.main).
Saif
  • 2,678
  • 2
  • 22
  • 38
  • Why I can't see the difference between the question and answer? – Mojtaba Hosseini May 17 '21 at 13:49
  • :D I found the answer but didnt know why it worked, so posted both working and non-working code in question and my findings in answer, so that it can be helpful for someone who faces similar issue :D, read the question again, it has 2 questions @MojtabaHosseini – Saif May 17 '21 at 13:53
  • Let me rewrite it for you ☺️ @MojtabaHosseini – Saif May 17 '21 at 13:57