Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Files are not readable in Swift Playground.

How to make files readable?

Same code runs well on Xcode terminal app, but fails on Swift Playground.

Demo code below.

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

Sample images:

XCode Terminal App Swift Playground

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
923 views
Welcome To Ask or Share your Answers For Others

1 Answer

I have to thank Nate Cook for first for his quick response and solid answer.

Just for case I share his answer from another post, which title is misleading.

See Nate's answer here: 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

Seems that there is no way to access files with Swift Playground outside of Playground sandbox. If you know how to access files outside of sandbox, you are welcome to share your solution!!

Show Package Contents

Resources Folder


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...