xcode – Swift游乐场 – 文件不可读

前端之家收集整理的这篇文章主要介绍了xcode – Swift游乐场 – 文件不可读前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
文件Swift Playground中无法读取.

如何使文件可读?

相同的代码在Xcode终端应用程序上运行良好,但在Swift Playground上失败.

演示代码如下.

import Foundation

println("Hello,World!")

var fname:String = "/Users/holyfield/Desktop/com.apple.IconComposer.plist"
var fm:NSFileManager = NSFileManager.defaultManager()

if(fm.fileExistsAtPath(fname)){
    println("File Exists")
    if(fm.isReadableFileAtPath(fname)){
        println("File is readable")
        var fd:NSData? = NSData(contentsOfFile: fname)
        println(fd?.length)
        let pl = NSDictionary(contentsOfFile: fname)
        println(pl?.count)
        println(pl?.allKeys)
    }else{
        println("File is not readable")
    }
}
else{
    println("File does not exists")
}

示例图片

解决方法

我必须感谢Nate Cook的第一个快速反应和坚实的答案.

只是为了案例,我从另一篇文章分享他的答案,哪个标题是误导的.

看到Nate在这里的答案:https://stackoverflow.com/a/26723557/2360439

Playgrounds are sandBoxed,so you won’t be able to just grab files from anywhere in your user folder. Here’s how to add that file to your
playground to make it accessible:

  • Find your “.playground” file in the Finder Right click and choose “Show Package Contents”
  • You should see “timeline.xctimeline”,“contents.xcplayground”,and “section-1.swift”
  • Make a new folder called “Resources” if it doesn’t exists yet.
  • Copy your files into Resources folder

似乎没有办法在Playground沙箱外使用Swift Playground访问文件.如果您知道如何访问沙箱外的文件,欢迎您分享您的解决方案!

原文链接:https://www.f2er.com/iOS/336062.html

猜你在找的iOS相关文章