Contents

URL

A value that identifies the location of a resource, such as an item on a remote server or the path to a local file.

Declaration

struct URL

Mentioned in

Overview

You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file’s last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use URLSession and its related classes to access the contents of remote resources.

URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as String by calling init(contentsOf:encoding:), or as a Data by calling init(contentsOf:options:).

As a convenience, you can use Swift’s async-await syntax to asynchronously access the contents of a URL through the resourceBytes and lines properties. These properties use the shared URLSession instance to load the resource.

URL defines a set of properties for common directories like documentsDirectory and cachesDirectory, some of which have distinct behaviors for backup or automatic purging. To make the best use of these directories, see Using the file system effectively.

Topics

Creating a URL from a string

Creating a file URL from a string path

Creating a file URL from a file path

Creating a file URL for a common directory

Creating a URL by resolving a bookmark

Creating a URL from a resource

Creating a URL by parsing

Accessing the parts of a URL

Accessing URL representations

Accessing resource values

Working with the data representation of a URL

Working with file URLs

Accessing common directories

Accessing home and user directories

Adding path components

Adding a path extension

Adding query items

Removing path components

Removing a path extension

Creating bookmarks

Checking reachability

Loading URL contents asynchronously

Working with promised items

Working with security scoped resources

Describing a URL

Formatting a URL

Using reference types

App Intents support

Structures

Initializers

See Also

URLs