Swift Playground - Files are not readable

前端 未结 3 670
失恋的感觉
失恋的感觉 2020-12-01 21:21

Files are not readable in Swift Playground.

How to make files readable?

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

3条回答
  •  隐瞒了意图╮
    2020-12-01 21:37

    There are several ways to do load files into a Swift Playground. I'll highlight the Image Literal, File Menu and Context Menu techniques.

    Image Literal technique

    This is the easiest and COOLEST. You simply drag a file from anywhere on your machine into the code and assign it via a let or var statement. GIF here.

    File Menu technique

    Choose File -> Add Files to "MyProjectName"

    See GIF of this here.

    Context Menu technique

    You can reveal the current playground in the Xcode (7.3.1) Project Navigator using the right-click menu. Upon revealing the current playground, you'll see a directory entitled Resources. Simply drag the file you want access to into that folder and watch the magic happen (given you've written the file access code).

    Example resource loading code

    Here's an example of doing this for showing an image:

    let url: NSURL! = NSBundle.mainBundle().URLForResource("IMG_4099", withExtension: "JPG")
    let imagePath = url.path
    let image = UIImage(contentsOfFile: imagePath!)
    let imageView = UIImageView.init(image: image)
    

    I've produced an animated GIF that demonstrates this in action. Here's a screengrab from that:

    Reading external code

    If you want to add auxiliary code in addition to resources, use the Sources folder.

    A note regarding the console

    The console area of Xcode's Playground interface will show you that the UIImage instance is nil when you load an image file outside the sandbox. If you entered a path you know exists, but the image isn't showing, ensure the UIImage instance isn't printing as nil.

提交回复
热议问题