Swift playgrounds with UIImage

IosUiimageSwiftXcode6Swift Playground

Ios Problem Overview


I am working with Xcode 6, and I'm trying to recreate the code demoed during session 401 "What's new in Xcode 6". I've added an image to Images.xcassets (called Sample) and within the playground file I'm trying to access this image, as demoed.

My code is as follows (like the demo):

var sample = UIImage(named: "Sample")

However, I can't get it to work like the demo. Am I missing something?

Ios Solutions


Solution 1 - Ios

Look at the iOS Developer Library->Playground Help and search"Resource Files" and you will find the answer

1、Open the .playground

2、Show the Project navigator by selecting View > Navigators > Show Project Navigator.

3、Drag the images to the Resources

Like follow:

enter image description here

Solution 2 - Ios

  1. Open the .playground file in Finder.
  2. Create a folder called Resources next to it.
  3. Add any images you want to this folder.
  4. In the playground press opt-cmd-1 to open the File Inspector. You should see the playground on the right. If you don't have it selected, press cmd-1 to open the Project Navigator and click on the playground file.

File Inspector

  1. Under 'Resource Path' choose 'Relative To Playground'
  2. Click the folder icon underneath and choose the Resources folder created earlier.

You should now have a bundle that you can use with the standard NSImage(named:"filename_without_extension"):

Working nsbundle image

Note: Because Xcode will frequently overwrite the .playground folder, I recommend using this method so the resources folder isn't getting constantly deleted and re-created.

Solution 3 - Ios

I had some trouble with this also.

Unfortunately, Chris' answer didn't work for me. I suspect perhaps a later beta release of Xcode 6 may have removed this setting.

Here's a solution as of Xcode 6.0 beta 4 (6A267N) available 21st July 2014. I would guess that this corresponds to the "Inside playground" option previously. That is where the Resources folder is within the playground package itself.

Here's how to set this up.

Using Finder - or if you're like me and use the awesome Path Finder - right select and choose Show Package Contents as follows:

enter image description here

That reveals the packages Resources folder:

enter image description here

Copying the image files into that folder will do the business:

let imageNames = ["back-button", "background", "bg_top"]
let images = imageNames.map { UIImage(named: $0) }

enter image description here

Solution 4 - Ios

For Xcode 9:

  • Select Resources folder
  • Right click then "Add files to "Resources""
  • Use it like: let image = UIImage(named: "no")

enter image description here

Solution 5 - Ios

As of Xcode 8 Beta 1, you can use Image Literals to import an image into an Xcode playground:

Start typing image to add an image literal:

Swift Image Literal

Select (or browse for) your image:

Image

See your image inline:

Inline

Solution 6 - Ios

> However, I can't get it to work like the demo. Am I missing something?

I'm not sure where you need to put the image to refer to it using only the name, but I got the same code to work by specifying the full path to the image, like:

var sample = UIImage(named: "/Users/my_user_name/Desktop/Image1234.jpg")

Having to use the full path seems more complicated than it should be, but it works and it let me move on to more interesting problems.

Solution 7 - Ios

You can find out the path of resourcePath using these commands in playground:

var bundle = NSBundle.mainBundle()
var path = bundle.resourcePath

Default for me was:

/Applications/Xcode6-Beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Agents

Solution 8 - Ios

I had difficulty getting this setup for an iOS playground, as opposed to an OS X playground. Trying to do it using bundles and relative paths makes it more complicated.

If you just want to get your hands on an image quickly, you can also just use absolute file path:

On iOS:

# iOS
let absoluteImagePath = "/absolute/path/to/image.png"
let image = UIImage(contentsOfFile: absoluteImagePath)

And on OS X

# OS X
let absoluteImagePath = "/absolute/path/to/image.png"
let image = NSImage(contentsOfFile: absoluteImagePath)

Solution 9 - Ios

On the iOS playground with XCode 6 beta 5 (and probably later) you can see the image inside the bundle:

  1. In the playground press Cmd+Opt+1 and click the arrow under the Resource Path (this will open Finder)

  2. Put your picture to this folder

  3. Access it with either

     let img = UIImage(named: "logo.png", inBundle: NSBundle.mainBundle(),
                       compatibleWithTraitCollection: nil)
    

    or

     let path = NSBundle.mainBundle().pathForResource("logo", ofType: "png")
     let img = UIImage(contentsOfFile:path)
    

    or in Swift 4:

     let path = Bundle.main.path(forResource:"logo", ofType: "png")
     let img = NSImage(contentsOfFile:path!)
    

Solution 10 - Ios

This is what worked for me on Xcode Version 6.1.1.

  1. Create Playground file under same directory as main storyboard.

    Folder Structure

  2. Open Utilities pane for Playground file, and click the right arrow in Resource Path section to add your images in that directory.

    Resource Path for Playground

  3. Test image within Playground file.

    Result

Solution 11 - Ios

Using XCode 6.3.1 and running playground in full simulator (iOS) I had to do the following:

  1. Find your .playground file in finder
  2. Right click it -> show package contents
  3. If it doesn't already exist, create a folder named Resources inside the package
  4. Add your image there

Then just instantiate with let i = UIImage(named: "filename.png")

Solution 12 - Ios

I have no idea why it is not working the easy way with PDF images.

I had to add this extension to load PDF images into my Playground:

extension UIImage {

	static func fromPDF(_ url: URL) -> UIImage? {
		var image: UIImage?
		guard
			let doc  = CGPDFDocument(url as CFURL),
			let page = doc .page(at: 1)
		else { return nil }

		let pageRect = page.getBoxRect(.mediaBox)
		let renderer = UIGraphicsImageRenderer(size: pageRect.size)

		image = renderer.image { ctx in
			UIColor.clear.set()
			ctx.fill(pageRect)
			ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
			ctx.cgContext.scaleBy(x: 1.0, y: -1.0)
			ctx.cgContext.drawPDFPage(page)
		}
		return image
	}
}

// Given the file "myImage.pdf" was added to your Playground's Resources folder.
let image = UIImage.fromPDF(#fileLiteral(resourceName: "myImage.pdf"))

It is based on this: https://developer.apple.com/forums/thread/90990

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoss GibsonView Question on Stackoverflow
Solution 1 - IosBruceView Answer on Stackoverflow
Solution 2 - IosChris HillView Answer on Stackoverflow
Solution 3 - IosMax MacLeodView Answer on Stackoverflow
Solution 4 - IosWilliam HuView Answer on Stackoverflow
Solution 5 - IosJALView Answer on Stackoverflow
Solution 6 - IosCalebView Answer on Stackoverflow
Solution 7 - Iosuser3715448View Answer on Stackoverflow
Solution 8 - IosalgalView Answer on Stackoverflow
Solution 9 - IosvoigerView Answer on Stackoverflow
Solution 10 - IostoadeadView Answer on Stackoverflow
Solution 11 - IoschadkouseView Answer on Stackoverflow
Solution 12 - IoslakaView Answer on Stackoverflow