System - free Swift example code
About 18 min
System - free Swift example code êŽë š
System - free Swift example code
Learn Swift coding for iOS with these free tutorials â learn Swift, iOS, and Xcode
Found 63 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....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....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:...How to check whether one date is similar to another
Appleâs
Calendar
object gives us lots of useful methods for evaluating dates in various ways. One of the most useful is the method isDate(_:equalTo:toGranularity:)
, which lets us compare two dates at a specific level of granularity: do these two dates occur in the same minute? The same hour? Or day, week, year? ...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....
How to compress and decompress data
Apple gives us dedicated API for compressing binary data, although annoyingly it exists on
NSData
without being bridged neatly to Swiftâs native Data
type. Fortunately, that conversion is trivial, so this functionality isnât hard to use....How to convert between camel case and snake case with Codable and keyEncodingStrategy
Most Swift developers use camel case for naming properties, which means we start with a lowercase letter then capitalize the first letter of second and subsequent words:
numberOfUsers
or powerLevel
. On the other hand, many web APIs prefer snake case, written as number_of_users
and power_level
, so if you need to convert camel case to snake case you need to use the keyEncodingStrategy
of JSONEncoder
, like this:...How to convert dates and times to a string using DateFormatter
If you want to get a string from a
Date
, Appleâs DateFormatter
class has everything you need: you can get short dates, long dates, dates with times, and can even go the opposite way to give you a Date
from a string....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....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:...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....
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 general
property that returns the shared system space for copying and pasting data between apps. Using this you can write text to the clipboard just like this:...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....How to decode JSON from your app bundle the easy way
If you want to load some JSON from your app bundle when your app runs, it takes quite a few lines of code: you need to get the URL from your bundle, load it into a
Data
instance, try decoding it, then catch any errors....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....
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:...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 UIApplication.willResignActiveNotification
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)....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
....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....
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....
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:...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....How to group user notifications using threadIdentifier and summaryArgument
If your app shows notifications that can be split into sensible groups â such as messages from a person, updates for a news story, scores from a sports match, and so on on â you can have iOS group them together using the
threadIdentifier
and summaryArgument
properties of UNMutableNotificationContent
. iOS will then show those messages together, rather than in a long chain mixed up with other messages....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....
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....
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....How to join an array of strings in a natural way
Swift provides the
ListFormatter
class as a built-in way of joining lists of strings into a single string so that the last item has âandâ before it, like a natural English string. So, rather than just getting âA, B, Câ you actually get âA, B and Câ â itâs much more suitable for user interfaces....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....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:...How to make one operation wait for another to complete using addDependency()
When working with multiple instances of
Operation
, youâll often want to queue up work that needs to be performed sequentially rather than all at once. If you want one operation to wait for another to complete before it starts, regardless of which operation queue either one is running on, you should use addDependency()
to make the sequence clear to the system....How to make tappable links in NSAttributedString
You can make interactive hyperlinks in any attributed string, which in turn means you can add interactive hyperlinks to any UIKit control. If you're working with
UITextView
(which is likely, let's face it), you get basic hyperlinks just by enabling the 'Links' data detector in Interface Builder, but that doesn't work for arbitrary strings â for example, maybe you want the words 'tap here' to be interactive....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:...
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....
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:...
How to parse JSON using JSONSerialization
If you want to parse JSON by hand rather than using
Codable
, iOS has a built-in alternative 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....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....
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....
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. ...
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:...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....
How to run an external program using Process
If youâre building an app for macOS or any other platform where you can run external programs, you can draw on Foundationâs
Process
class to do almost all the work for you....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....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:...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....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:...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....
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:...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....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....
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....
How to show a relative date and time using RelativeDateTimeFormatter
If you want to format dates and times in the form â5 hours agoâ or â3 months agoâ, Apple gives us a dedicated formatter called
RelativeDateTimeFormatter
. This is localized for many languages, so youâll automatically get back strings that work in French, German, Chinese, and more, all depending on the userâs locale....How to show the price of an SKProduct
StoreKit products come with
price
and priceLocale
properties but it takes a little effort to combine those two together in order to show a user-friendly price in your interface....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:...
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!...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....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....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:...
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....
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....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....
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....
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:...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....