NEW! Master Swift design patterns with my latest book! >>

System

Found 56 articles in the Swift Knowledge Base for this category:

 

How do you read from the command line?

If you're working on a command-line app for macOS or Linux, you'll probably want to read and manipulate commands typed by the user. This is easy to do using the readLine() function, which reads one line of user input (everything until they hit return) and sends it back to you.... Continue Reading >>

How to cache data using NSCache

Here's an easy win for you that will make your apps immediately much better: NSCache is a specialized class that behaves similarly to a mutable dictionary with one major difference: iOS will automatically remove objects from the cache if the device is running low on memory.... Continue Reading >>

How to cancel a delayed perform() call

You can make a method call run after a number of seconds have elapsed using perform(_:withObject:afterDelay:), like this:... Continue Reading >>

How to check whether your other apps are installed

iOS lets you check for the existence of other apps, but you do need to declare them in your Info.plist file, and you may need to provide an explanation to the App Review team if you try to query too many apps or apps that aren’t yours.... Continue Reading >>

How to convert HTML to an NSAttributedString

You can create an NSAttributedString directly from HTML, including support for a wide range of formatting, using a special initializer and passing in NSAttributedString.DocumentType.html for your document type.... Continue Reading >>

How to convert units using Unit and Measurement

iOS 10 introduced a new system for calculating distance, length, area, volume, duration, and many more measurements. Let’s start with something simple. If you’re six feet tall, you’d create a Measurement instance like this:... Continue Reading >>

How to copy objects in Swift using copy()

There are two main complex data types in Swift – objects and structs – and they do so many things similarly that you'd be forgiven for not being sure exactly where they differ. Well, one of the key areas is down to copying: two variables can point at the same object so that changing one changes them both, whereas if you tried that with structs you'd find that Swift creates a full copy so that changing the copy does not affect the original.... Continue Reading >>

How to copy text to the clipboard using UIPasteboard

You can write to and read from the iOS clipboard by using the UIPasteboard class, which has a generalPasteboard() method that returns the shared system method of copying and pasting data between apps. Using this you can write text to the clipboard just like this:... Continue Reading >>

How to create a peer-to-peer network using the multipeer connectivity framework

The MultipeerConnectivity framework is designed to allow ad hoc data transfer between devices that are in close proximity. The connection is started managed for you by iOS, but you're responsible for presenting useful interface to your users and for understanding the data that is being sent and received.... Continue Reading >>

How to create rich formatted text strings using NSAttributedString

Attributed strings are strings with formatting attached, which means fonts, colors, alignment, line spacing and more. They are supported in many places around iOS, which means you can assign a fully formatted string to a UILabel and have it look great with no further work.... Continue Reading >>

How to detect low power mode is enabled

When a user has enabled low-power mode you probably want to avoid doing CPU-intensive work: not only is the system less able to give you resources, but you always want to respect the user's wishes and help their battery last as long as possible.... Continue Reading >>

How to detect the dominant language of a text string

The NSLinguisticTagger class has dedicated code to help you identify the dominant language of a text string. Before I show you the code, there are three important provisos:... Continue Reading >>

How to detect when your app moves to the background

There are two ways to be notified when your app moves to the background: implement the applicationWillResignActive() method in your app delegate, or register for the UIApplicationWillResignActive notification anywhere in your app. This particular notification is sent as soon as your app loses focus, meaning that it's triggered when the user taps the home button once (to return to the home screen) or double taps the home button (to enter multi-tasking).... Continue Reading >>

How to detect which country a user is in

Being able to provide users with location-specific information immediately makes your app more useful, but asking for a precise location brings up a permission alert and might make them suspicious. Fortunately there's a coarse-grained way you can figure out a user's locate without asking for location permission: Locale.... Continue Reading >>

How to download files with URLSession and downloadTask()

URLSession is designed to make network transfers as easy as possible, and a great example of that is its downloadTask()` method. This fetches the contents of a URL you specify, saves it to a local file, then calls a completion handler so you can manipulate the file – all in one.... Continue Reading >>

How to find the path to a file in your bundle

It’s common to store resource data like text files and sound effects inside your bundle, but loading them must be done in a particular way to avoid problems.... Continue Reading >>

How to find the user's documents directory

Every iOS app gets a slice of storage just for itself, meaning that you can read and write your app's files there without worrying about colliding with other apps. This is called the user's documents directory, and it's exposed both in code (as you'll see in a moment) and also through iTunes file sharing.... Continue Reading >>

How to format dates with an ordinal suffix using NumberFormatter's ordinalStyle

As of iOS 9.0, Apple introduced a simple way to make ordinal style numbers, which is a fancy way of saying 1st, 2nd, 3rd or 100th – the kind of numbers you normally write for dates, for example. This uses the NumberFormatterStyle.ordinal style of writing numbers with NumberFormatter, like this:... Continue Reading >>

How to generate a random identifier using UUID

A UUID is a universally unique identifier, which means if you generate a UUID right now using UUID it's guaranteed to be unique across all devices in the world. This means it's a great way to generate a unique identifier for users, for files, or anything else you need to reference individually – guaranteed.... Continue Reading >>

How to generate random numbers in iOS 8 and below

iOS 9.0 introduces Gameplay and its great new random tools, but if you have to support iOS 8.0 and earlier here's the code you're looking for:... Continue Reading >>

How to handle the HTTPS requirements in iOS with App Transport Security

iOS doesn’t let you work with HTTP web data by default, because it's blocked by something called App Transport Security that effectively requires data to be transmitted securely. If possible, you should switch to HTTPS and use that instead, but if that's not possible for some reason – e.g. if you're working with a third-party website – then you need to tell iOS to make exceptions for you.... Continue Reading >>

How to identify an iOS device uniquely with identifierForVendor

Early iOS releases gave every device a unique identifier, but this was soon abused by developers to identify individual users uniquely – something that Apple really dislikes. So, Apple removed the truly unique identifier and instead introduced an identifier for each vendor: a UUID that's the same for all apps for a given developer for each user, but varies between developers and between devices.... Continue Reading >>

How to insert images into an attributed string with NSTextAttachment

If you've ever tried to lay out multiple UILabels mixed in with UIImageViews, you'll know it's almost impossible to make them line up correctly even after you add dozens of Auto Layout rules.... Continue Reading >>

How to load and save a struct in UserDefaults using Codable

The Codable protocol makes it easy to load and save native Swift types to JSON, and with a little typecasting you can get that data into UserDefaults so it’s safe.... Continue Reading >>

How to make an action repeat using Timer

Timers are a great way to run code on a repeating basis, and iOS has the Timer class to handle it for you. First, create a property of the type Timer!. For example:... Continue Reading >>

How to make tappable links in NSAttributedString

You can make tappable hyperlinks in any attributed string, which in turn means you can add tappable hyperlinks to any UIKit control. If you're working with UITextView (which is likely, let's face it), you get basic tappable hyperlink just by enabling the "Links" data detector in Interface Builder, but that doesn't work for arbitrary strings – for example, maybe you want the word "click here" to tappable.... Continue Reading >>

How to make the device vibrate

All iPhones have a built-in motor to create vibration effects, and if you just want a quick vibration it takes just one line of code:... Continue Reading >>

How to make your app open with a custom URL scheme

Custom URL schemes allow your app to be launched from anywhere else in the system, but you can also use them to query which of your other apps are installed and even pass data.... Continue Reading >>

How to open a URL in Safari

If you want the user to exit your app and show a website in Safari, it's just one line of code in Swift. I'll make it three here because I'll create the URL in the code too, then safely unwrap it:... Continue Reading >>

How to parse JSON using JSONSerialization

The built-in iOS way of parsing JSON is called JSONSerialization and it can convert a JSON string into a collection of dictionaries, arrays, strings and numbers in just a few lines of code.... Continue Reading >>

How to pass data between two view controllers

If you have a value in one view controller and want to pass it to another, there are two approaches: for passing data forward you should communicate using properties, and for passing data backwards you can either use a delegate or a block.... Continue Reading >>

How to post messages using NotificationCenter

iOS notifications are a simple and powerful way to send data in a loosely coupled way. That is, the sender of a notification doesn't have to care about who (if anyone) receives the notification, it just posts it out there to the rest of the app and it could be picked up by lots of things or nothing depending on your app's state.... Continue Reading >>

How to read names in a string using NSLinguisticTagger

Foundation has a built-in class to parse strings of text, and it includes some useful options to extra names of people, places, organizations, and more.... Continue Reading >>

How to read the contents of a directory using FileManager

If you want to work with files FileManager almost certainly has the answer, and it's no different in this case: it has a method called contentsOfDirectory(atPath:) that lists all the files in a specific directory. For example, we could have it list all the files in our app's resource directory like this:... Continue Reading >>

How to read your app’s version from your Info.plist file

All iOS apps must store an app version number in their Info.plist file, but there’s no build-in way to get that as a string you can use in your code.... Continue Reading >>

How to run code after a delay using asyncAfter() and perform()

There are two ways to run code after a delay using Swift: GCD and perform(_:with:afterDelay:), but GCD has the advantage that it can run arbitrary blocks of code, whereas the perform() method runs methods.... Continue Reading >>

How to run code asynchronously using GCD async()

iOS gives you two ways to run code asynchronously: GCD and performSelector(inBackground:). The first option looks like this:... Continue Reading >>

How to run code at a specific time

You can use perform(_:with:afterDelay:) to run a method after a certain number of seconds have passed, but if you want to run code at a specific time – say at exactly 4pm – then you should use Timer instead. This class is great for executing code repeatedly at a specific time interval, but it's also great for running code at an exact time that you specify.... Continue Reading >>

How to run code on the main thread using GCD async()

Swift offers you two ways to run code on the main thread: GCD and performSelector(onMainThread:). The first option looks like this:... Continue Reading >>

How to run code when your app is terminated

If you need to execute code when your app isn’t running, there are several options open to you depending on what you’re trying to do.... Continue Reading >>

How to save and load objects with NSKeyedArchiver and NSKeyedUnarchiver

You can write any kind of object to disk as long as it supports the NSCoding protocol – which includes strings, arrays, dictionaries, UIView, UIColor and more right out of the box. To write to disk, use this:... Continue Reading >>

How to save user settings using UserDefaults

All iOS apps have a built in data dictionary that stores small amounts of user settings for as long as the app is installed. This system, called UserDefaults can save integers, booleans, strings, arrays, dictionaries, dates and more, but you should be careful not to save too much data because it will slow the launch of your app.... Continue Reading >>

How to send notifications asynchronously using NotificationQueue

Any notifications posted using NotificationCenter are delivered synchronously, which means all observers get notified simultaneously and execute all their code before control gets passed back to the the poster of the notification.... Continue Reading >>

How to set local alerts using UNNotificationCenter

Local notifications are messages that appear on the user's lock screen when your app isn't running. The user can then swipe to unlock their device and go straight to your app, at which point you can act on the notification.... Continue Reading >>

How to show the price of an SKProduct

StoreKit products come with price and priceLocale property, but it takes a little effort to combine those two together in order to show a user-friendly price in your interface.... Continue Reading >>

How to spell out numbers using NumberFormatter's spellOut style

iOS makes it easy to convert numbers like 10 or 100 into their written equivalents: "ten" and "one hundred", and it even handles other languages. For example, to convert the number 556 into "five hundred fifty-six", you would use this code:... Continue Reading >>

How to stop the screen from going to sleep

You can stop the iOS screen sleeping by using the isIdleTimerDisabled property of your application. When set to true, this means the screen will never dim or go to sleep while your app is running, so be careful – you don't want to waste your user's battery life!... Continue Reading >>

How to store UserDefaults options in iCloud

iOS has a built-in iCloud sync system called NSUbiquitousKeyValueStore, but to be honest it's pretty unpleasant to work with. Fortunately, other developers have written simple wrappers around it so that you can forget about iCloud and focus on the interesting things instead – i.e., the rest of your app.... Continue Reading >>

How to synchronize code to drawing using CADisplayLink

Lots of beginners think Timer is a great way to handle running apps or games so that update code is executed every time the screen is redrawn. Their logic is simple: update the app every 60th of a second and you're perfectly placed for smooth redraws.... Continue Reading >>

How to use Core Motion to read accelerometer data

Core Motion makes it ridiculously easy to read the accelerometer from iPhones and iPads, and it even takes care of managing how the accelerometer and gyroscope work together to report orientation. To get started import the Core Motion framework like this:... Continue Reading >>

How to use Core Spotlight to index content in your app

One particularly popular feature in iOS 9.0 is the ability to have your app's content appear inside the iOS Spotlight search so that users can search it alongside their other device content.... Continue Reading >>

How to use multithreaded operations with OperationQueue

There are lots of ways to work with Grand Central Dispatch (GCD) on iOS, but OperationQueue is particularly powerful because it lets you control precisely how many simultaneous operations can run and what quality of service you need, while also letting you schedule work using closures. You can even ask the operation queue to wait until all its operations are finished, which makes scheduling easier.... Continue Reading >>

How to use Touch ID to authenticate users by fingerprint

Touch ID is an easy and secure way for users to authenticate themselves, so its no surprise that it's caught on so quickly among apps. Authenticating with Touch ID automatically uses the fingerprints registered by the user when they set up Touch ID, and you never have access to those fingerprints, which means it's both low-friction and extra-secure.... Continue Reading >>

Measuring execution speed using CFAbsoluteTimeGetCurrent()

It’s often important to know at runtime how long it took for some code to run. For example, you might want to make sure your game’s AI takes at least two seconds to think before making its move, so that players don’t get confused when there’s no thinking time.... Continue Reading >>

NSTextEffectLetterpressStyle: How to add a letterpress effect to text

You can add a subtle embossing effect to any text in your app using NSAttributedString and NSTextEffectLetterpressStyle. As an example, this code creates an attributed string using 24-point Georgia Bold in red, with Apple's letterpress effect applied, then writes it into a label:... Continue Reading >>

What is the first responder?

Most of UIKit has a concept of responders baked deep into the system, but it’s not common you need to work with it directly. It’s Apple’s implementation of a design pattern called the Chain of Responsibility: UIKit asks one component if it can respond to an action, but if it can’t it gets passed to another component, and if that can’t respond then it gets passed on and on until something can respond – it’s a chain of responders.... Continue Reading >>

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions, all written for Swift 4.

Upgrade to the premium experience

Get all 40 projects in PDF and ePub, plus exclusive content that will take your Swift learning to the next level – buy the Hacking with Swift book today!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>