为什么 swift 无法识别我的资源?

Why does swift not recognise my resource?

Swift 告诉我我的文件不存在,不幸的是我自己找不到目录。我是否错误地使用了 URL 作为资源方法,或者我是否只需要找到一种删除可选括号的方法?当我直接引用这个对象时,它可以工作,但我需要找到一种方法来创建我的队友也可以使用的路径。

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)    
}

捆绑打印URL:

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

您有两个问题:

  1. "\(bundleURL)"NSURL 的值包装在 Optional(...) 额外文本中。
  2. URLForResource 已经给了你一个 NSURL。无需从中创建另一个 NSURL

只需使用bundleURL。不需要 eventsFile 变量。

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