Want to learn how to develop your own apps for Mac OS X?
Good news – Apple makes developing for OS X incredibly easy – and in this tutorial series we’ll show you how. You’ll learn how to create your first app for OS X – even if you’re a complete beginner.
- In this first part you’ll first learn about how to obtain the tools you need to develop for OS X. Then, using an app you’ve downloaded as an example, you’ll take a tour of Xcode, discovering how to run an app, edit code, design the UI and debug it.
- In part two, you’ll take a step back from Xcode to learn about the components that make up an OS X app. From how an app starts, through how the UI is constructed all the way to handling user interaction.
- You’ll get your hands dirty in the final part – building your first ever OS X app. Starting from nothing, you’ll soon have a simple app up and running on your mac!
So what are you waiting for? The world of desktop apps awaits!
Note: Here’s some guidance of where to begin with this series:
- If you are new to Swift, this series assumes Swift knowledge, so first check out our Swift tutorials to get a great introduction.
- If you already have iOS experience, this first part of the series will be review. Take a quick look through the topics to make sure and then skip straight ahead to the next part of the series.
- Otherwise, keep reading – this series is for complete beginners – no experience of developing for iOS or OS X is required!
Prerequisites
To become an OS X developer, you will need a few things:
- Mac running OS X. The OS X operating system only runs on Apple computers, so you need a Mac both to develop and run OS X apps. If you’re wondering which Mac to buy, we recommend a Mac Mini with extra memory and a solid state or Fusion drive; it’s the best balance between cost and power.
- An AppleID. In order to download the tools from the App Store, you’ll need an AppleID.
- Xcode. This is the IDE and toolchain used to create OS X apps. You’ll learn how to install this in the next section.
Once you’ve built your app, and you want to upload it to the App Store to be distributed, you’ll also need to pay for an Apple developer account. But this is not a requirement until you are ready to send your app out to the world.
Obtaining Tools
Unlike some other platforms, developing for OS X requires the installation of one tool – known as Xcode. Xcode is an IDE that includes everything you need to develop iOS, watchOS and OS X apps.
If you don’t have Xcode already, click on the Apple icon in the upper left of your menu and select App Store to open the Mac App Store.
Search for Xcode and download it:
Once it has downloaded and installed, open Xcode from your Applications folder. The first time you open Xcode it’ll ask to install some additional components. Go ahead and let it, entering your password if required.
You’ll then be presented with the Xcode welcome screen:
Congratulations, you’ve successfully installed Xcode! Read on to learn all about what it can do.
Beta versions of Xcode
Before moving on to describing the power of Xcode, it’s worth taking a few minutes learning about beta versions of Xcode.
When Apple releases new updates to Xcode (often to support new features in OS X, iOS and watchOS) they go through an agressive cycle of beta releases. These releases include the new features, but consequently many bugs. If you are interested in developing an app which leverages these new features, you’ll need to download the latest beta from Apple.
This tutorial requires Xcode 7, since the sample project used in this tutorial has been updated to the Swift 2.0 programming language. There are two cases:
- If the App Store version of Xcode is Xcode 7 at the time of reading this tutorial, you are all set!
- If the App Store version of Xcode is Xcode 6 at the time of reading this tutorial, you’ll need to install a beta version of Xcode 7 – keep reading to learn how.
To get the latest beta version of Xcode, visit developer.apple.com, click on Resources, Xcode, and then Download. Follow the link to download the latest version of Xcode beta there.
Note you can install a beta version of Xcode alongside the stable version, so there’s no problem with continuing work on projects that aren’t ready for upgrade.
The download is a DMG, so you can install by dragging the Xcode app across into Applications in the usual way. You’ll then have two versions of Xcode in your applications folder:
Run Xcode-beta and then you’re ready to continue on!
Hello World!
Xcode is an Integrated Development Environment (IDE) which means that it is a collection of all the tools you need, from source code editing, compilation through to debugging and UI design.
When you open Xcode it allows you to create a new project, or open an existing one. You can also open an existing project by double clicking on an Xcode project or workspace in Finder:
Creating a new app
For most of this tutorial you’ll tour Xcode via a sample app, but first things first – you can’t start learning about a new platform without first creating a “Hello World” app!
To do this, select Create a new Xcode project from the Xcode welcome screen:
The template chooser allows you to decide how Xcode will configure your new project. In the OS X \ Application section you can see the three different core OS X app types:
The three different app types are as follows:
- Cocoa Application: An OS X desktop app – with a window-based UI. Cocoa is the name of the framework upon which all OS X applications are built.
- Game: Games built using Apple’s SpriteKit or SceneKit frameworks.
- Command Line Tool: A utility that runs in a shell, and has a text-based UI.
Select Cocoa Application, and click Next. On the screen that follows, set the Product Name to HelloWorld, check the language is set to Swift and that Use Storyboards is checked:
Click Next, and choose a location on disk to save your project.
This creates a new, empty project ready for you to craft into your amazing app. The first thing you’ll want to do is build and run it to check that it’s all working.
Running your app
Whether you’ve opened an existing app or created a new one, the most important thing you’ll want to do is to build and run it.
This involves compiling all of the code you’ve written into machine code, bundling up the resources required by the app and then executing it. This process is complex, but luckily Xcode has your back. To build and run your project simply press the play button on the toolbar:
You can also build and run your app with the ⌘R keyboard shortcut.
Your HelloWorld app is currently looking a bit empty – and doesn’t even say hello! You’re going to fix that now.
Adding Text
You’re going to update the user interface (UI) of your app to make it into a true “Hello World” app, and to do this you’re going to use a tool called Interface Builder (IB). You’ll learn much more about Interface Builder later in this tutorial – for now, you just need to know enough to add some text to the layout.
Find the Main.storyboard file in the Project Navigator, and click on it:
This opens the storyboard file in Interface Builder – you can see an outline of your entire app:
The lower component (entitled “View Controller”) represents the visual appearance of your app. You’re going to add a text label to this to create your “Hello World” app.
Find the Object Library in the lower right part of the Xcode window. Type label into the search box and locate the Label entry:
Drag a label from the Object Library onto the empty View Controller scene canvas:
A label represents a static piece of text – with no user interaction – perfect for your Hello World app. You don’t want it to say “label” though – you’re going to update that next.
To configure the label, select it and then open the Attributes Inspector (the 4th tab) on the right hand side of the Xcode window. Set the title to “Hello OS X!”, and update the font to be size 40:
You may see that the label is no longer sized correctly – next you’ll fix that and set it to the correct position.
You position UI elements in OS X using a system called Auto Layout – which allows you to specify positions and sizes of UI elements in terms of their relationships. You want to put your “Hello OS X!” label in the center of the window – so you’re going to add constraints to achieve this.
Select the label once again, and click the Align button in the bottom bar (the second from the left). Check both the Horizontally in Container and the Vertically in Container boxes, and ensure that they are both set to 0. Select Items of New Constraints in the Update Frames selection box before finally clicking the Add 2 Constraints button:
This will update the storyboard to position and size your label correctly.
Build and run your app (either by clicking the play button, or using the ⌘R keyboard shortcut) to see your “Hello World!” Mac OS X app:
Introducing HubEvent
You’ll continue learning how to make projects from scratch and code OS X apps in later parts of this series, but for the rest of this tutorial you’ll focus on learning more about Xcode itself.
To help with that, I’ve created a sample project for you called HubEvent that you’ll work with for the rest of this tutorial. This way you can get a tour of Xcode with a real-world project.
Download the HubEvent starter project, unzip it and double click on HubEvent\HubEvent.xcodeproj in Finder to open it in Xcode.
Build and run HubEvent sample project and you’ll see it compile and then launch:
HubEvent uses the public GitHub API to pull down all the events for a user, and displays a summary of them in a table. As you select each row of the table, the raw JSON associated with that event is displayed in the panel below.
Xcode Core Functionality
HubEvent is a fairly simple app, but is complex enough to demonstrate the core functionality of Xcode. The remainder of this tutorial will cover the following:
- Code Editor. All OS X apps have a code component, and HubEvent is no different. The code in HubEvent is responsible for downloading the data from the GitHub API, and wiring it up to the user interface.
- Interface Builder. You’ve already used Interface Builder when you build your “Hello World!” app. You’ll learn more about how this powerful tool allows you to build up the split-window UI used in HubEvent.
- Asset Catalog. All image assets are stored inside asset catalogs – you’ll discover how to replace the standard app icon with something more interesting.
- Debugging. Everybody makes mistakes when writing code and building apps and Xocde’s debugger makes identifying and fixing bugs a whole lot easier.
- Documentation. OS X apps are build on top of some extremely advanced system frameworks, and nobody can remember exactly how to use each and every one of them. Luckily Apple creates high-quality documentation and has integrated it with Xcode to make it easy to find answers to your questions.
Code Editor
Apps are built primarily from code, written in the Swift programming language. You can also use Objective-C to write apps for OS X, but Apple introduced Swift in 2014, and was very clear that it is the langauge of the future. HubEvent is written in Swift.
One of the views available in Xcode is the Code Editor, which is activated whenever you open a source code file. To see it, select WindowController.swift from the Controllers group in the Project navigator.
In the main section of the Xcode window, you can now see the source code associated with the Window Controller. Find the following line:
// The shared data model let sharedDataStore = DataStore(username: "rwenderlich", type: .Network) |
This line is selecting the source of the GitHub event data – here choosing Ray’s username (rwenderlich
).
Try changing rwenderlich
to a different GitHub username – for example sammyd
. Then, build and run your app as you did before. You’ll see the new user’s events listed in the app:
Well done! You’ve changed your first code in an OS X app!
The code editor includes many powerful features to assist you as your write code, including autocompletion and QuickLook documentation.
Interface Builder
Although it is possible to build the user interface of an OS X app entirely in code, since UI is inherently visual, proceeding in this manner isn’t very intuitive.
Xcode includes a tool called Interface Builder (IB), which is a fully-featured visual design tool that allows you to build your UI from reusable components.
The files which make up these visual interfaces are called Storyboards – a name inspired by the film industry. In the same way that a storyboard is used to depict scenes in a film, and the progression through it, a storyboard in an app depicts the scenes and the flow between them.
To see a storyboard in Interface Builder, select Main.storyboard in the Project navigator:
This storyboard includes the layout for the entire app. You can see how the table at the top of the app is split out as a separate entity from the JSON viewer at the bottom.
To get a really quick feel for interface builder, you’re going to change the color of the icon in the left hand column.
Although being zoomed out allows you to get a good view of the entire storyboard, you can’t edit a zoomed out storyboard. Zoom in to the EventList VC scene using ⌘+. This is the scene that contains the table:
Use the button in the bottom left corner to Show Document Outline. This is a panel along the left hand side of Interface Builder which shows you the hierarchy of components that make up the current scene.
If you click on the purple ⌘ symbol in the table view, you’ll highlight the corresponding Table Cell View row in the Document Outline. Since you want to access the text field inside this cell, click on the ⌘ again. Now you’ll have the row selected as in the previous image.
Once you’ve selected this text field, you can configure various attributes associated with it, which determine its appearance.
If the Utilities panel is not visible down the right hand side of Xcode, use the button in the toolbar to show it:
This panel can display many different inspectors, but the one you want now is the Atrributes Inspector. Select it now and you’ll find the Text Color attribute:
Tap on the purple color bar, and you’ll see a colors panel. Use this to select a different color – e.g. yellow:
Now you can build and run HubEvent again to see the effect your change has had:
Asset Catalog
In addition to code and user interfaces, your app will also need some assets such as artwork. Due to the different screen types (e.g. retina and non-retina), you often need to provide multiple versions of each asset. To simplify this process, Xcode uses Asset Libraries to store and organize the assets that accompany the app.
HubEvent already has the default asset library, called Images.xcassets. Select it in the Project navigator to reveal its content:
When you create a new app, the template includes an asset library, with just one entry – the app logo. This is exactly the state of the asset library in HubEvent. You can see the different asset types you can create by right clicking in the left pane of the library:
Currently the app icon for HubEvent is the default OS X icon:
Since the app icon is provided by the asset catalog, you’re going to replace it with something more appropriate. Click on the AppIcon asset:
When you provide an app icon for an app, you have to provide it in many different sizes and densities for use around the system. As a demonstration, you’re going to add one of these sizes to see the app icon change.
Use Finder to locate rw_icon.png in the unzipped directory you downloaded. Then drag this from Finder into the Mac 512pt 2x cell in the AppIcon asset:
Now build and run the app again and you’ll see the updated icon in the dock:
Debugging
Nobody is capable of writing code that works perfectly every time, and therefore you’re likely to spend time trying to fix problems in your code. You’ll soon find that it’d be really helpful to be able to stop your app at a particular line of code and investigate the values of variables. This is precisely the functionality provided by a debugger.
Once again, Xcode is here to help. It has an integrated debugger that makes runtime investigation of your code really easy. To demonstrate some of its functionality, you’re going to use it.
Open Value Transformers\CodeStringFormattingTransformer.swift by selecting it in the Project navigator.
Find the following line in the code:
return NSAttributedString(string: unescaped, attributes: attributes) |
Click in the gutter to the left of this line to insert a breakpoint:
A breakpoint marks the line in your code at which point execution will stop. Your app will pause at this point to allow you to investigate the state.
Build and run the app. You’ll see the app start, before Xcode comes back to the foreground. You’ll see the line you added the breakpoint to highlighted:
This means that your app has started running, and then reached this line of code. It has paused here to allow you to investigate.
The bottom pane in Xcode shows you the state of the variables at the current point of execution, including their variables.
This particular method is removing escaped characters from the JSON downloaded from the GitHub API. You can see the input string s
and the resultant string unescaped
.
You can progress to the next line of execution with the stepover button:
Or to continue the program execution, use the continue button:
Note that continuing will then run the program until it comes across another breakpoint.
To remove a breakpoint, you can drag it out of the gutter until the pointer changes to a x.
Fixing a bug with the debugger
To see how debugging works, you’re going to fix a real-world bug! You’ve had reports that if you change HubEvent to use a disk-based data source instead of network then it ignores your choice – and still queries the network. Your job is to find this bug and fix it.
First, to change the app into disk-mode instead of network-mode, open WindowController.swift, locate the line that creates the sharedDataStore
, and update it to match the following:
let sharedDataStore = DataStore(username: "rwenderlich", type: .Disk) |
Now run up the app, and confirm that the data is indeed still being pulled from the network (the on-disk data was acquired in April 2015).
To debug this problem, you’re going to add a break point at the point the data store is created to find out what’s happening. Open DataStore.swift, and add a breakpoint on the line that contains super.init()
.
Run the app and wait for it to pause at the break point. Use the debug browser to locate the dataProvider
property within self
:
Notice that the type next to it is GitHubData.GitHubDataNetworkProvider
. This doesn’t sound right – why would it be using an object called network when it’s reading off disk.
Now take a look further up the file, and you’ll find where this dataProvider
object is created:
switch type { case .Network: dataProvider = GitHubDataNetworkProvider() case .Disk: dataProvider = GitHubDataNetworkProvider() } |
This is a switch statement that decides what kind of provider it needs to create – why does it create a GitHubDataNetworkProvider
for the .Disk
type? This is the bug!
Replace the .Disk
case to match the following:
case .Disk: dataProvider = GitHubDataFileProvider() |
Now re-run the app, and it’ll pause on the same breakpoint. Check the type of the dataProvider
property once again:
The type now looks correct – use the Continue program execution button to run the app:
Yay! The app is now reading from the disk-based store, rather than over the network. Well done – you’ve fixed your first OS X bug!
Documentation
Xcode has a couple of integrated ways to get access to documentation for system frameworks. The first is the ability to show a tooltip containing the most salient information about a class or method.
As an example, open Controllers\WindowController.swift and inside the transformedValueClass()
method, Option-Click on NSString
:
The second method of accessing documentation shows you the full documentation in a dedicated browser. To access this, either click on the Reference link at the bottom of the tooltip, or click the Window \ Documentation and Reference menu. Then search for NSString
to pull up the documentation:
Fixing a bug with documentation
Let’s see how you can use Xcode’s documentation to fix another bug.
When HubEvent first loads, you’ll notice that the divider between the table and the JSON view is positioned very high:
If you try to drag the divider down, you’ll see that it snaps to the middle of the window, and is then immovable. This is the behavior you’d like, but the divider should be in the correct position when the app starts.
You can achieve this by adding a single line to the viewWillAppear()
method inside the SplitViewController.swift file. Use the documentation browser to search for NSSplitView
, and read about the setPosition(_:, ofDividerAtIndex:)
method. Then use this method on the splitView
property in the aforementioned method, passing in view.bounds.height / 2.0
for the position.
Where To Go From Here?
Here’s the finished project for this Max OS X development tutorial.
At this point, you have a birds-eye overview of the most important aspects of Xcode. In the next article you’ll learn about the anatomy of an app, and finally move on to creating your first OS X app.
Apple has a huge amount of documentation for OS X – all available on the Developer Portal.
If you have any questions or comments then please join in below or on the forums.
The post Mac OS X Development Tutorial for Beginners Part 1: Intro to Xcode appeared first on Ray Wenderlich.