ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Print Hello World in Swift to the iPhone

Updated on December 9, 2016

Introduction

This tutorial will show you how to print “Hello World” to the iPhone.

We will print Hello World to an iPhone simulator on a Mac running Xcode, and we will then print Hello World to an iPhone/iPad device.

See my hub “Print Hello World in Swift” to get a brief introduction to the Swift programming language.

https://turbofuture.com/computers/Print-Hello-World-in-Swift

Xcode

Xcode runs on Mac OS X. Download and install the latest Xcode from the App Store.

Launch Xcode

Launch Xcode by double clicking on its icon in the Applications folder once you have installed it.

Choose Create a new Xcode Project

In the Choose a template for your new project window, select iOS, Application and highlight Single View Application. Then click Next.

Enter the Product name, Organization Name, and Organization Identifier. Select Swift as the Language, and iPhone as the device. Leave the other options as the defaults.

Then Click Next.

Navigate to the folder where you want to save this project. Then click on Create.

On the left pane, click and highlight AppDelegate.swift from the list. The AppDelegate.swift file contains the source code for creating a basic standard iOS app.

Apple has already put in all the necessary functions and code for a complete iOS app that uses a single view. This template app does "nothing" but it does run and displays a white empty screen.

To view it running on an iPhone simulator, you will need to select which device to emulate. This is in the option to the right of the play and stop buttons.

To compile and run the app, click on the Play button, or you can go to the Product menu and select Run.

You will need to minimize the Xcode window so as to show the simulator.

The app displays a nice white screen.

Print Hello World

We’re now going to write “Hello World” to this screen.

Click the Stop button on the top of the Xcode project window or select Stop from the Product menu.

The Simulator will still run until you quit out of the simulator.

If you minimize the Xcode window, you will see a simulated iOS device with the HelloWorld app icon displayed with other app icons.

What is the command to Print to the iPhone screen?

Let’s first go to Apple’s API Reference web site at:

https://developer.apple.com/reference/

You can click on any of the links to go to that topic’s page. It will give you an overview of what APIs are available under that section. From there, we can find out which function we should use.

We are going to click the UIKit link in the App Frameworks section because, for one thing, our project is using this framework.

You can see at the top of our program in Xcode the following statement:

import UIKit

This tells the app to use the UIKit framework.

The UIKit framework contains numerous classes. Scrolling down the UIKit page will show the list of the classes in UIKit.

The UILabel Class

In GUI environments, the term label is given to the read-only text that you see displayed in the different locations on a window which often describes the particular input box or that particular area of the window.

It is easier to make use of a label and change what it’s text should be displaying rather than using drawing primitives to draw raw text on the screen. Labels are usually implemented as UI objects in a UI API library and so what this means is we don’t have to programmatically worry about redrawing the text in an application window if something was displayed over it previously. Once we use a label object, we can place it on the application window and set the text. It stays “permanent” until we change the text. It gets redrawn automatically for us if something displays over it and then moves away.

In iOS, the UILabel Class is a class which was inherited from the UIView class. Each iOS app will have at least one view. The UILabel will then be placed on the view that needed to show the label.

Scroll the page to see the list of functions (or methods) and properties for UILabel.

Going back to the Xcode screen, we will now select the ViewController.swift source file from the left pane of the project.

The ViewController.swift file is another source file in our HelloWorld project. It created a view for our app which displays as a blank white screen, and we will put the label object on this view.

viewDidLoad

We need to modify the viewDidLoad function so that we can add the label to the view object correctly.

override func viewDidLoad() {
 super.viewDidLoad()
 //Do any additional setup after loading the view, typically from a nib.
}

We need to make use of the UILabel class and set the coordinates of where the label object will appear in the default view and specify the colour we want the text to be and what the text to be displayed is.

We will add the following to the original function:

let myText=UILabel(frame:CGRectMake(0,100,200,20))
myText.textColor = UIColor.blackColor()
myText.text="Hello World"
self.view.addSubview(myText)

The function will now look like this :

override func viewDidLoad() {
 super.viewDidLoad()
 //Do any additional setup after loading the view, typically from a nib.
 let myText=UILabel(frame:CGRectMake(0,100,200,20))
 myText.textColor = UIColor.blackColor()
 myText.text="Hello World"
 self.view.addSubview(myText)
}


Let’s press the play button to run this.

We will now have Hello World displayed on our iPhone simulator.

For those who have an Apple device such as the iPhone or iPod, this can be plugged into the Mac OS laptop or desktop via the USB cable. When you want to run your app on your device, just select this device in Xcode instead of the simulated device before you run.

You should be able to click the play button or choose the Product->Run option and it will install the app on the iPhone or iPad device and launch it. You will also see the HelloWorld icon on the device and you can just tap it to launch it.

Common Errors when trying to run on the iPhone or iPad

Could not find Developer Disk Image

You may get the error message “Could not find Developer Disk Image” when trying to run the program on your attached iPhone or iPad.

What this usually means is that your device is running the latest update of the iOS and your Xcode is not running the latest version. The first thing that needs to be done is to update the Mac OS X to the latest update. Once your OS has been updated, you can then upgrade the Xcode version.

Once Xcode has been upgraded, you can then launch it. Xcode will now give you the choice to use the latest Swift version. Accept the choice.

Open the HelloWorld project. It will go through the source code of the HelloWorld project and try to convert the project and source code to be compatible with the latest version of Swift and the API. It will highlight any changes required. Click Save to accept the changes.

Select the Device again and try to run the program by clicking the play button or selecting Product->Run.

Could not launch “HelloWorld”

You may get the message that you need to "Verify the Developer App Certificate for your account is trusted on your device...."

To resolve this, open settings on your device, and navigate to General->Device Management, then select your Developer App certificate to trust it. Simply just click on whatever is shown and choose to accept the certificate since it’s your own device.

Bundle Identifier not unique

When trying to run the project on the device for the first time, the build process may fail and give an error that the Bundle Identifier is not unique. For our purposes, you can just append a number after the Bundle Identifier name i.e. hello.HelloWorld becomes hello.HelloWorld2. Check the Deployment info and make sure the Deployment Target matches the iOS version of the device.

This settings screen can be reached by highlighting the HelloWorld project on the left pane, then clicking on the square icon to the left of General. Then under TARGETS, select the HelloWorld target. Then click on General.

Other things to Watch Out For

When you plug your iPhone or iPad device in, make sure the device is unlocked before plugging it into the Mac.

iTunes may be trying to sync with the device. Make sure this completes or quit out of iTunes.

Sometimes Xcode will try to “process symbols” on the device after you have plugged it in. It may not allow you to build the program and run it on your device while this is happening and it will tell you that your device is busy.

Conclusion

We have been able to write Hello World to the iPhone simulator relatively easily. However, there were some challenges to writing Hello World to the actual iPhone device.

I hope that the reader was able to successfully write to the iPhone device with the steps above including the troubleshooting steps.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)