Random Remote Images in Swift

Eliot Fowler
JAM Courses
Published in
2 min readOct 11, 2017

While working on a new feature for the JAM iOS app, I needed to mock out objects that will be returned by our API. Specifically, I wanted random images of a certain size. A lot of the legwork is readily available — I just combined different existing solutions to solve my problem.

I used a combination of random colors and placehold.it to mock the images.

Placeholdit returns images of a specific size and optional color using the following format: http://placehold.it/{width}x{height}/{hex_color}. I needed a static width and height (400x400) and of a random color.

First, I made use of an extension on CGFloat that I already had:

extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}

This allows me to write CGFloat.random() to get a random float between 0 and 1.

Next, I used an extension on UIColor that I found from StackOverflow to generate a random color (using the same CGFloat extension):

extension UIColor {
static func random() -> UIColor {
return UIColor(red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0)
}
}

This allows me to write UIColor.random() to get a random color — cool!

The last thing I needed was to get the hex code of that color. StackOverflow to the rescue again!

var hexString: String {
let colorRef = cgColor.components

let r: CGFloat = colorRef[0]
let g: CGFloat = colorRef[1]
let b: CGFloat = colorRef[2]

return NSString(format: "%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255))) as String
}

(slightly modified from the StackOverflow post for readability)

This allows me to write UIColor.random().hexString to get the 6-digit hex representation of the color.

Now all I need to do is combine this with the URL to get random remote images:

let randomColorHex = UIColor.random().hexString
let url = URL(string: "http://placehold.it/400x400/\(randomColorHex)")

With this, I have a url like: http://placehold.it/400x400/0015AE which generates this image:

There are lots of times when building new features for the JAM iOS app that we need to mock API responses and specifically the image URLs they return. This allows me to quickly drop in images of different sizes and colors with no trouble at all.

--

--