【问题标题】:Swift 2.0 code works in Xcode but not in PlaygroundSwift 2.0 代码在 Xcode 中有效,但在 Playground 中无效
【发布时间】:2015-08-05 18:40:18
【问题描述】:

我正在学习 Swift,并且一直在试图弄清楚我无法加载文件的原因感到沮丧。事实证明,该代码在 Xcode 中有效,但在 Playground 中无效。这是什么原因?

代码如下:

func testFileLoad(){
    let myFilePath: String = "/Users/clay/Desktop/test.txt"
    let t: Bool = NSFileManager.defaultManager().fileExistsAtPath(myFilePath)
    print(t)

    let s: String = try! String(contentsOfFile: myFilePath, encoding: NSUTF8StringEncoding)
    print(s)

    do {
        let p: String = try String(contentsOfFile: myFilePath, encoding: NSUTF8StringEncoding)
        print(p)
    } catch {
        print("nope")
    }
}

在 Xcode 的测试模块中运行,它可以正常工作并将我希望的内容打印到控制台。

Test Suite 'Selected tests' started at 2015-08-05 14:24:15.977 
Test Suite 'swiftgraphTests' started at 2015-08-05 14:24:15.978 
Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' started. 
true 
this is a test 
this is a test 
Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' passed (0.001 seconds). 
Test Suite 'swiftgraphTests' passed at 2015-08-05 14:24:15.979.      
    Executed 1 test, with 0 failures (0 unexpected) in 0.001 (0.001) seconds 
Test Suite 'Selected tests' passed at 2015-08-05 14:24:15.979.   
    Executed 1 test, with 0 failures (0 unexpected) in 0.001 (0.002) seconds

在操场上,我得到了这个:

我在这里做错了什么?我是否在不当使用游乐场?

【问题讨论】:

    标签: xcode swift swift2 swift-playground


    【解决方案1】:

    如果你去菜单

    “查看”->“调试区”->“显示调试区”

    您将看到完整的错误:“您无权从 Playground* 访问文件系统。”

    解决方法是在 Playground 中使用其项目导航器包含文件。

    进入菜单

    “视图”->“导航器”->“显示项目导航器”

    然后将您的文件拖放到“资源”文件夹中。

    然后使用 NSBundle 获取路径。

    func testFileLoad() {
    
        // get the file path for the file from the Playground's Resources folder
        guard let path = NSBundle.mainBundle().pathForResource("test", ofType: "txt") else {
                print("Oops, the file is not in the Playground")
                return
        }
    
        // keeping the examples from your question
        let s: String = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        print(s)
    
        do {
            let p: String = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
            print(p)
        } catch {
            print("nope")
        }
    
    }
    
    testFileLoad()
    

    *实际上,您只能访问包含您的 Playground 共享数据的 /var/ 文件夹,而 Playground 只是提供了一个快捷方式。 Playground 导航器中的这个文件夹实际上代表/var/ 文件夹,并且对于每个 Playground 都是唯一的。你可以用 NSBundle 查看它的地址:

    NSBundle.mainBundle().resourcePath
    

    【讨论】:

    • var 文件夹是否在 Playground 文件的捆绑包中?
    • 我已经用关于这个文件夹的更多细节更新了我的答案。
    【解决方案2】:

    可能是权限问题。可能在您的 XCode 项目中,您拥有一组在 Playground 中不可用的权限。

    【讨论】:

    • 您在操场上可以访问的唯一目录可以通过NSSearchPathForDirectoriesInDomain(.DocumentDirectory, .UserDomainMask, true)获得
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2013-01-16
    • 2011-12-17
    • 2019-04-28
    • 2016-02-24
    相关资源
    最近更新 更多