Category: Swift

Xcode 9 uiimage image not shown
September 30th, 2017 by ronny

Xcode 9 uiimage image not shown

Working on some ios apps created with Xcode 8 and your images don’t show after upgrading to Xcode 9? Took me awhile to find out why. Maybe you see this message in the console: “Could not load the image referenced from a nib in the bundle with identifier”.

Xcode 9 uiimage image not shown because Xcode 9 wants you to keep all your image files inside the Assets.xcassets file. Uiimage will let you select image files outside the Assets, but will make the uiimage control to not show at all.

If Xcode 9 uiimage image not shown move your images inside the Assets file, select the image again in the uiimage properties and give it another go. That worked for me.

Also, read Swift Change UIButton text


Happy coding!

Posted in Swift, Xcode Tagged with: ,

Swift Capitalize
April 2nd, 2017 by ronny

Swift Capitalize, How to

Swift Capitalize is done with a string instance property. Check the example below to see how to use it. There is also a link at bottom to Apples Swift documentation.
let str = “first, second, third”

This will output: First, Second, Third

Swift Capitalize

It will capitalize every word in this string. Lets remove the commas and see what happens.

Change str = “first second third”

The output now will be: First Second Third

Check Apple Swift Capitalizion documentation for more information about the string instance property.

Swift Capitalizion
Produce a string with the first character from each word changed to the corresponding uppercase value.

Posted in Swift, Xcode Tagged with: ,

Swift Debian
March 19th, 2017 by ronny

Swift Debian 8 (Jessie)

Swift, Apples new programming language, to take over for Objective C has been open source for some time now. It only took at short time before it was available for various Linux Distros. The latest Swift version in the official Debian repos are 2.3.1. If you want version 3.x of swift Debian you need download and install it your self. Here is how to do it.

Use sudo or root to create directories and install Swift.

We will install Swift Debian in the /opt/swift/build folder. So first:
cd /opt

Then create the new folder for our Swift build.
mkdir -p swift/build

Change to the new directory before we download Swift.
cd swift/build

Download the swift build from

The Swift Debian is still compressed, so we need to extract it. Make sure you downloaded the file to /opt/swift/build directory.
tar zxvf swift-3.0.2-RELEASE-ubuntu14.04

Now we need to make sure our system knows where the swift compiler is stored. For immediate effect you can paste this line.
export PATH=/opt/swift/build/swift-3.0.2-RELEASE-ubuntu14.04/usr/bin:"${PATH}"

But once you logged out, that setting will be gone. To make that permanent go to your home folder. Once back in your home folder (/home/what-ever-your-user-is-named), you want to edit the .profile file.
vim .profile

And paste this in at the end of the file.

To make sure it works, you can disconnect or log out (if it is a local system) and log back in. Try to type in swift and press enter. The swift console should now open. You might run into some errors if you try to compile anything now. So we need to install a bunch of packages. Install these packages by typing (or copy paste)
apt-get install curl gcc python-dev python-pip libffi-dev python-setuptools sqlite3 git-core git cmake ninja-build clang uuid-dev libicu-dev icu-devtools libbsd-dev libedit-dev libxml2-dev libsqlite3-dev swig libpython-dev libncurses5-dev pkg-config

Now your system should be able to compile and make executable files from swift source codes. However if you are new to swift there is one thing you need to know. Create a folder for each project you make. Because your main source file needs to be called main.swift. If not the compiler will return error code 1.

You are now ready to use both the swift console and compile your files. Give it a test.

Create a folder and create main.swift And here is short sample file you can try to compile.
let message = “Hello Debian World”

Compile the file by typing
swiftc main.swift

And run the file by typing

Happy coding

Posted in Debian, Swift Tagged with:

didMove never get called
March 11th, 2017 by ronny

didMove never get called in Xcode?

didMove never get called when creating a new project with Xcode using the Game template. I selected Swift and SpriteKit. I found this issue when I was following a course on, and I couldn’t get a simple project to run like in the course videos. Creating a new project after deleting the one I was working on, after trying to debug the error, gave me the same result. didMove never get called. I did only one change to the project created with game template. That was to put in print(“didMove did run”). But it never was.

The only way I would get the didMove to run was calling the scene like this in the GameViewController.
let scene = MainMenuScene(size: CGSize(width: 1536, height: 2048))

Tried to google, and I found this one post on Stack Overflow with the same issue. He said it was caused by a period in his project name. Crazy, but I did use a – in my project name. Was only a test project, so calling it physics-test was not a good idea. I renamed it to PhysicsTest, and the didMove was called.

Not sure if it is a language setting issue or anything. I’m using english language and Norwegian region settings on my computer. Not sure if that got anything to do with it, but in the tutorial video I was following it worked great using – in the project name.

Anyway, if you experience didMove never get called in Xcode, it might be worth removing any non letter and number characters.

Happy coding!

Posted in Swift, Xcode Tagged with: , ,

Swift Change UIButton text
June 9th, 2016 by ronny

Swift Change UIButton text

How to in Swift change UIButton text?
A common mistake, also done by myself some time ago, is to try to change it through an IBAction. You can use an IBAction, but probably not the way you think. A common mistake is to do something like this:
button.text = “Some text”
This will give a compiler error if you try something like that. I would make sense to be able to do it like that. Like in Visual Studio you can change text like that.

I’ll show you two methods on how you can change your UIButton text programatically.

Swift Change UIButton text – Method 1 (IBOutlet)

In the first method we will use an IBOutlet to change the button text. First create a UIButton somewhere on the storyboard. Second create the IBOutlet the normal way. Call the IBOutlet “button”. And you should end up with something like this:

@IBOutlet weak var button: UIButton!

Now in the viewDidLoad function we will try to set a new title for the button. Try put in this into the viewDidLoad function:
button.setTitle(“Ready”, forState: .Normal)

If you try to run your code in the simulator now, your app will start up with the button called Ready. The text from the storyboard should never even appear in your app. I have pasted the complete source code from the example below.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var button: UIButton!

override func viewDidLoad() {


// Do any additional setup after loading the view, typically from a nib.

button.setTitle(“Ready”, forState: .Normal)



Swift Change UIButton text – Method 2 (IBAction)

Some might tell you that you can not change the UIButton text without an IBOutlet. In some cases it might be more practical to use an IBOutlet, if your button should change text without any user interaction. If you want the text to change after the user clicked the button, the IBOutlet is not needed. You can do that from the IBAction directly. Here is how.

In your example create an IBAction for your UIButton. Notice the first word in the parenthesis. It says sender, or at least it should say. That sender represent the UIButton. And you can use the same setTitle function directly with the sender. Check out this example.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {



@IBAction func buttonClicked(sender: AnyObject) {

sender.setTitle(“Sender”, forState: .Normal)



Try to run that example an see what happens. As soon you click the button, the text will change to “Sender”.

That is how you in Swift change UIButton text.

Check out UIButton in the swift documentation here

See how to do it on video

Happy texting!

Posted in Programming, Swift, Xcode Tagged with: , ,

Swift string input
May 15th, 2016 by ronny

Swift string input

Swift string input has become a lot easier than since I posted an article about it. In my previous article Swift string input required you to create your own function to read a input line. Then one viewer commented on my YouTube video a different method for Linux users. His method had a readLine function. When I tested this with Xcode in OS X it worked just fine. And I’m almost sure it wasn’t that easy about a year ago.

Here is the function we need to use

I tried to test it with Playground too, but I could not get it to work there.

Swift string input example

import Foundation

print("What is your name? ")
if let yourName = readLine() {
print("Hello, \(yourName)")

The output will be something like this.
What is your name?
Hello, Ronny

If this is all new to you, and want to have a look at the old method. Just for the fun of it. You will find that in this article

If you want to see a video on how to do it, you can see it below. I have updated my old video. It is still out there, but go for the updated version.

Thats how you do String input with Swift for OS X now (and Linux).

Happy coding!

Posted in Swift Tagged with: , , ,

swift play mp3
May 9th, 2016 by ronny

Swift play mp3 from your app

Swift play mp3 from your app with this small example. To make swift play mp3 files we need to start with importing AVFoundation. That is where the audio player is.

import AVFoundation

Next we will create a variable for our music player.

var player = AVAudioPlayer()

Then we create a function to initialise the music player, and prepare the song. If you are using it as a background music you can run the function from viewDidLoad.

This is what you need to set up the player.

func initAudio() {
let path = NSBundle.mainBundle().pathForResource("music", ofType: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: NSURL(string: path)!)
player.numberOfLoops = -1
} catch let err as NSError {

If you plan to start the music programmatically or from a button you will need to remove the line. Thats all the code you need to load and play a mp3 file.

Lets do an example with starting and stopping the music from a button. I assume you have created both and Action and IBOutlet for the button. Even though the IBoutlet can be skipped and solved in a different way.

The IBOutlet is called button. I’m not going thru how to create an IBOutlet here now. The following code will create a function you can call from your IBAction.

func playPause() {
if player.playing {
button.setTitle("Play music", forState: UIControlState.Normal)
} else {
button.setTitle("Pause music", forState: UIControlState.Normal)

Now as I mentioned you can skip the IBOutlet if the only purpose is to change the button text. If you other things to the button you might need it. If not here is how you can skip that. First we need to take the code above (the code inside the playPause function) and paste it into the IBAction function. Then we change the button.setTitle(“Play music”, forState: UIControlState.Normal), to sender.setTitle(“Play music”, forState: UIControlState.Normal). Sender will be the same as button. Here is the complete code for the IBAction.

@IBAction func btnPlayMusic(sender: AnyObject) {
if player.playing {
sender.setTitle("Play music", forState: UIControlState.Normal)
} else {
sender.setTitle("Pause music", forState: UIControlState.Normal)

To download a working example, please go to my github account here:

You will need to add your own mp3 file to that project. Mine was called music.mp3

Thats it for swift play mp3.

Happy playing!

Posted in Swift, Xcode Tagged with: , ,

swift send email
May 7th, 2016 by ronny

Swift send email from your iOS app

Swift send email from your iOS app. How do we do that…
It was easier than I first thought. At least with this method. Using the MessageUI and have the app to pre-fill an email and using iOS mail to send it.

First we need to import the MessageUI. We will do that from the view controller in my example code. By the way you can download the example code from my github. Just go to and download the code.

The we will need to setup the MFMailComposeViewControllerDelegate.

// Set delegate
class MyViewController: UIViewController,MFMailComposeViewControllerDelegate {
// Code goes here

My swift send email example only contains a send button on the user interface. Not showing here how to link an action to a button. But inside the button action code we do something like this:

@IBAction func btnSendEmail(sender: AnyObject) {
let email = MFMailComposeViewController()
email.mailComposeDelegate = self
email.setSubject("Subject goes here")
email.setMessageBody("Some example text", isHTML: false)
email.setToRecipients([""]) // the recipient email address
if MFMailComposeViewController.canSendMail() {
presentViewController(email, animated: true, completion: nil)

The code above will populate all fields needed to send you email. Subject field, recipient address and message body. You can of course edit any of these in the email that pops up before you send it. Because you will need to confirm the mail. Just like any other email you send. Just that you dont have to enter the information your self. The fields doesn’t have to be fixed in your code either. You can have dynamic values changed programatically based on anything you want.

Last we will need to enter the function in order for the delegate to work. And that is something like this:
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
dismissViewControllerAnimated(true, completion: nil)

Now you have all the code you need to send emails from your app.

Thats it for swift send email.

Happy emailing!

Posted in Swift, Xcode Tagged with: , ,

Swift loops
January 15th, 2016 by ronny

Swift loops

Some basic introduction to Swift loops.

Swift Loops: For loop

For loops are the same as the traditional C loops. If you have experience from C/C++ you already know this well. This is structured like this.

for initialisation; condition; increment {

An example on how this looks in real life. We here initialise an variable called counter. The variable can of course be named what ever you want.

for var counter = 0; counter < 10; counter++ {

This little example will print out the numbers from 0 to 9. When setting the condition to < 10, it means the for loop will run as long as counter is below 10. As soon as the counter reach the number 10, it will stop.

Swift Loops: For-In

As far as I know this is new with Swift. But if you know C/C++ (and probably others) it is very similar to For Each loops.

For-In loops runs your statements for each item in a sequence. That sequence can be from a number to another number. Like 0 to 10 as in the example above. Or it can be for each item in an collection, like an array. Lets look at two different ways of using For-In loops.

First example show how to use it like a regular for loop.

for counter in 0...9 {

You might notice we didn’t write 0…10. That is because 0…9 is not a condition, it is items we want to run through. So 0…9 in For-In loops equals Counter=0; Counter<10; Counter++ with regular For loops.

We can also run through arrays with For-In loops. Here is an array example.

let myCars = ["Ferrari", "Porsche", "Lada", "Skoda"]
for car in myCars {

This will print out all the cars in the myCars array.

Swift Loops: While

Same as with for loops, while loops works like traditional C/C++ while loops. Like for loops while loops have an condition. But there no increment part in while loops. You need to take care of that your self, if thats how you want to run the while loop. We will look at that.

To use while about the same way as for loops.

var counter = 0
while counter < 10 { print(counter) counter++ } This will print out the numbers 0 through 9. And as you see the counter increments with the other statements inside the while loop. You can also set the while condition to true. And use a break statement to end the while loop. Here is an example on how to do that.

index = 0
while true {
if index > 9 {

Swift Loops: Repeat While

Repeat while are similar to do while from traditional C. And it works the same way. The format of a repeat while loop is:

repeat {
} while condition

So like the last while example, we need to use statements to manipulate the conditions to end the loop. Here is a very simple example on a repeat while loop.

var repeats = 0
repeat {
} while repeats < 10

Like all the others example on this page, this will print out the numbers from 0 to 9.

Here is Apples swift documentation about control flow

Thats it for this time.

Happy looping!

Posted in Programming, Swift, Xcode Tagged with: , , , , ,

Swift Array
January 9th, 2016 by ronny

Swift array

Swift Array

An array in Swift, and any other programming language who support arrays, is a list of data. Those data can be any datatype. Integers, double, float, string and even classes. I will just show a few examples here. For a complete list and full documentation I suggest you head over to Apples Swift documentation, by click that link.

Swift array of integers

Say we need a list of integers for our software. Some pre-declared integers in a list of integer constants. Because we dont need to change them. Here is how to do that.

let myIntegers = [1, 3, 5, 10, 25, 100, 1000]

Ok, so how do we use that array of constants? I need to print the first and the last item now.

print(myIntegers[0])  // Printing the first item

print(myIntegers[6])  // Printing the last item

print(myIntegers.last)  // Printing the last item

So what if myIntegers was variables instead of constant? And I wanted to change the value of the 1st, 2nd and the last one?

myIntegers[0] = 10 // Changing the first item

myIntegers[1] = 15 // Changing the second item

MyIntegers.last = 99 // Changing the last item

Swift Array – Empty

Seems easy enough. But I need an empty array to populate later in my software. How do I do that?

var myIntegers = [Int]() // Declare an empty array of type Int

So how do I add items to this

myIntegers.append(5) // Your array now contain 1 value. The value 5.

Swift Array – insert

Actually I need to insert a new value before the one I added. Can I do that? Yes.

myIntegers.insert(12, atIndex:0) // The value 12 was inserted at the beginning of the array.

You can use this to insert values where ever you want in the array.

Swift Array – remove

I have a huge array, and I need to remove my 5th value and the last value. Is that even possible? Yes.



Swift Array – remove duplicates

My string array that  contains html links has a lot of duplicates. Is it possible to remove duplicates easily? Yes it is.

First you convert the array to a Set and then back to an Array. Set doesn’t contain duplicates, since it is not a list like an array. Here is how.

myStringArray = Array(Set(myStringArray))    // Your duplicates are now gone.

Swift Array – default value

Can I declare an array with a default value? I need an array of 10 values with the same value until I change them.

var myDefaultArray = [Double](count: 10, repeatedValue: 5.0)

Thats it for now about array. If you want to learn more and specific situations about array, I suggest you head over to

Happy arraying!

Posted in Programming, Swift, Xcode Tagged with: , , ,