Search code examples
iosswifturldirectorybundle

Why does swift not recognise my resource?


Swift is telling me my file does not exist and unfortunately I cannot find the directory myself. Am I using the URL for resource method incorrectly or do I just need to find a way of removing the optional brackets? When I refer to this object directly it works but I need to find a way of creating a path my team mates can use as well.

override func setUp()
{
    super.setUp()
    let bundleURL = NSBundle.mainBundle().URLForResource("meetingexample", withExtension: "ics")
    let eventsFile = NSURL(fileURLWithPath: ("\(bundleURL)"))
    //let eventsFile = NSURL(fileURLWithPath: docFolderURL.URLByAppendingPathComponent("/meetingexample.ics"))
    content = try! String(contentsOfURL: eventsFile, encoding: NSUTF8StringEncoding)    
}

Print of bundleURL:

Optional(file:/Users/GB112922/Library/Developer/CoreSimulator/Devices/EF6A2594-6B31-4E38-B46D-2F3AAAF25210/data/Containers/Bundle/Application/35E04003-072F-476E-957E-98C70B792539/CallIn.app/meetingexample.ics)`


Solution

  • You have two issues:

    1. "\(bundleURL)" is wrapping the value of the NSURL in the Optional(...) extra text.
    2. URLForResource is already giving you an NSURL. There's no need to create another NSURL from it.

    Just use bundleURL. There is no need for the eventsFile variable.

    override func setUp()
    {
        super.setUp()
        let bundleURL = NSBundle.mainBundle().URLForResource("meetingexample", withExtension: "ics")
        content = try! String(contentsOfURL: bundleURL, encoding: NSUTF8StringEncoding)    
    }