One Logo Pool Ball
Foundation · IOS API REFERENCE

URL

struct · iOS 8.0+ · SDK 27.1

struct 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. 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 ``Data/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.

Members (104)

get · iOS 8.0+

standardizedFileURL

TypeScript
get standardizedFileURL(): string
Swift declaration
var standardizedFileURL: URL { get }

A standardized version of the path of a file URL. If the `isFileURL` is false, this method returns `self`.

get · iOS 8.0+

baseURL

TypeScript
get baseURL(): (string) | null
Swift declaration
var baseURL: URL? { get }

The base URL. If the URL is itself absolute, then this value is `nil`.

get · iOS 8.0+

isFileURL

TypeScript
get isFileURL(): boolean
Swift declaration
var isFileURL: Bool { get }

A Boolean that is true if the scheme is `file:`.

get · iOS 8.0+

absoluteURL

TypeScript
get absoluteURL(): string
Swift declaration
var absoluteURL: URL { get }

The absolute URL. If the URL is itself absolute, this returns `self`.

get · iOS 8.0+

description

TypeScript
get description(): string
Swift declaration
var description: String { get }

A textual representation of this instance. Calling this property directly is discouraged. Instead, convert an instance of any type to a string by using the `String(describing:)` initializer. This initializer works with any type, and uses the custom `description` property for types that conform to `CustomStringConvertible`: struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) // Prints "(21, 30)" The conversion of `p` to a string in the assignment to `s` uses the `Point` type's `description` property.

method · iOS 8.0+

standardize

TypeScript
standardize(): void
Swift declaration
mutating func standardize()

Standardizes the path of a file URL. If the `isFileURL` is false, this method does nothing.

static · iOS 8.0+

bookmarkData

TypeScript
static bookmarkDataWithContentsOf(url: string): ArrayBuffer
Swift declaration
static func bookmarkData(withContentsOf url: URL) throws -> Data

Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.

method · iOS 8.0+

bookmarkData

TypeScript
bookmarkDataOptionsIncludingResourceValuesForKeysRelativeTo(options?: NSURL_BookmarkCreationOptions, keys?: (Array<URLResourceKey>) | null, url?: (string) | null): ArrayBuffer
Swift declaration
func bookmarkData(options: URL.BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data

Returns bookmark data for the URL, created with specified options and resource values.

get · iOS 8.0+

relativePath

TypeScript
get relativePath(): string
Swift declaration
var relativePath: String { get }

The relative path of the URL if the URL conforms to RFC 3986, otherwise nil. This is the same as `path` if `baseURL` is `nil`. - Returns: The relative path, or an empty string if the URL has an empty path.

get · iOS 8.0+

standardized

TypeScript
get standardized(): string
Swift declaration
var standardized: URL { get }

A version of the URL with any instances of ".." or "." resolved in its path.

static · iOS 16.0+

homeDirectory

TypeScript
static homeDirectoryForUser(user: string): (string) | null
Swift declaration
static func homeDirectory(forUser user: String) -> URL?

Returns the home directory for the specified user.

get · iOS 16.0+

homeDirectory

TypeScript
static get homeDirectory(): string
Swift declaration
static var homeDirectory: URL { get }

The home directory for the current user. This URL is the equivalent of the shell value `~/`. Complexity: O(1)

get · iOS 8.0+

pathExtension

TypeScript
get pathExtension(): string
Swift declaration
var pathExtension: String { get }

The path extension of the URL, or an empty string if the path is an empty string.

get · iOS 15.0+

resourceBytes

TypeScript
get resourceBytes(): URL_AsyncBytes
Swift declaration
var resourceBytes: URL.AsyncBytes { get }

The URL's resource data, as an asynchronous sequence of bytes. Use this property with Swift's `for`-`await`-`in` syntax, to read the contents of a URL byte-by-byte. To wait for the entire resource to load, use the ``URLSession`` method ``URLSession/data(from:delegate:)`` with the `await` keyword.

get · iOS 16.0+

userDirectory

TypeScript
static get userDirectory(): string
Swift declaration
static var userDirectory: URL { get }

The user home directories directory. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

get · iOS 8.0+

absoluteString

TypeScript
get absoluteString(): string
Swift declaration
var absoluteString: String { get }

The absolute string for the URL.

get · iOS 16.0+

musicDirectory

TypeScript
static get musicDirectory(): string
Swift declaration
static var musicDirectory: URL { get }

The music directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

get · iOS 8.0+

pathComponents

TypeScript
get pathComponents(): Array<string>
Swift declaration
var pathComponents: [String] { get }

The path components of the URL, or an empty array if the path is an empty string.

get · iOS 8.0+

relativeString

TypeScript
get relativeString(): string
Swift declaration
var relativeString: String { get }

The relative portion of a URL. If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.

static · iOS 8.0+

resourceValues

TypeScript
static resourceValuesForKeysFromBookmarkData(keys: Array<URLResourceKey>, data: ArrayBuffer): (URLResourceValues) | null
Swift declaration
static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues?

Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.

method · iOS 8.0+

resourceValues

TypeScript
resourceValuesForKeys(keys: Array<URLResourceKey>): URLResourceValues
Swift declaration
func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues

Return a collection of resource values identified by the given resource keys. This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources. When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values. Only the values for the keys specified in `keys` will be populated.

get · iOS 16.0+

trashDirectory

TypeScript
static get trashDirectory(): string
Swift declaration
static var trashDirectory: URL { get }

The trash directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

get · iOS 16.0+

cachesDirectory

TypeScript
static get cachesDirectory(): string
Swift declaration
static var cachesDirectory: URL { get }

The standard directory for discardable cache files. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

init · iOS 8.0+ · Deprecated in iOS 100000.0

init

TypeScript
static initFileURLWithPathRelativeTo(path: string, base?: (string) | null): string
Swift declaration
init(fileURLWithPath path: String, relativeTo base: URL?)

Creates a file URL that references the local file or directory at the given path, relative to a base URL. - Parameters: - path: The location in the file system. - base: A base URL to resolve the path against. If an empty string is used for the path, the system interprets it as ".".

init · iOS 8.0+ · Deprecated in iOS 100000.0

init

TypeScript
static initFileURLWithPathIsDirectoryRelativeTo(path: string, isDirectory: boolean, base?: (string) | null): string
Swift declaration
init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?)

Creates a file URL that references the local file or directory at the given path, relative to a base URL. - Parameters: - path: The location in the file system. - isDirectory: A Boolean value that indicates whether the path references a directory. - base: A base URL to resolve the path against. If an empty string is used for the path, the system interprets it as ".". - Note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.

init · iOS 8.0+ · Deprecated in iOS 100000.0

init

TypeScript
static initFileURLWithPathIsDirectory(path: string, isDirectory: boolean): string
Swift declaration
init(fileURLWithPath path: String, isDirectory: Bool)

Creates a file URL that references the local file or directory at the given path. - Parameters: - path: The location in the file system. - isDirectory: A Boolean value that indicates whether the path references a directory. If an empty string is used for the path, the system interprets it as ".". - Note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.

init · iOS 8.0+ · Deprecated in iOS 100000.0

init

TypeScript
static initFileURLWithPath(path: string): string
Swift declaration
init(fileURLWithPath path: String)

Creates a file URL that references the local file or directory at the given path. - Parameter path: The location in the file system. If an empty string is used for the path, the system interprets it as ".".

get · iOS 16.0+

moviesDirectory

TypeScript
static get moviesDirectory(): string
Swift declaration
static var moviesDirectory: URL { get }

The movies directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

static · iOS 16.0+

currentDirectory

TypeScript
static currentDirectory(): string
Swift declaration
static func currentDirectory() -> URL

The working directory of the current process. Calling this property will issue a `getcwd` syscall.

get · iOS 8.0+

debugDescription

TypeScript
get debugDescription(): string
Swift declaration
var debugDescription: String { get }

A textual representation of this instance, suitable for debugging. Calling this property directly is discouraged. Instead, convert an instance of any type to a string by using the `String(reflecting:)` initializer. This initializer works with any type, and uses the custom `debugDescription` property for types that conform to `CustomDebugStringConvertible`: struct Point: CustomDebugStringConvertible { let x: Int, y: Int var debugDescription: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(reflecting: p) print(s) // Prints "(21, 30)" The conversion of `p` to a string in the assignment to `s` uses the `Point` type's `debugDescription` property.

get · iOS 16.0+

desktopDirectory

TypeScript
static get desktopDirectory(): string
Swift declaration
static var desktopDirectory: URL { get }

The desktop directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

get · iOS 9.0+

hasDirectoryPath

TypeScript
get hasDirectoryPath(): boolean
Swift declaration
var hasDirectoryPath: Bool { get }

A Boolean that is true if the URL path represents a directory.

get · iOS 16.0+

libraryDirectory

TypeScript
static get libraryDirectory(): string
Swift declaration
static var libraryDirectory: URL { get }

The library directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

get · iOS 8.0+

lastPathComponent

TypeScript
get lastPathComponent(): string
Swift declaration
var lastPathComponent: String { get }

The last path component of the URL, or an empty string if the path is an empty string.

get · iOS 16.0+

picturesDirectory

TypeScript
static get picturesDirectory(): string
Swift declaration
static var picturesDirectory: URL { get }

The pictures directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

method · iOS 8.0+

setResourceValues

TypeScript
setResourceValues(values: URLResourceValues): void
Swift declaration
mutating func setResourceValues(_ values: URLResourceValues) throws

Sets the resource value identified by a given resource key. This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources. `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.

static · iOS 8.0+

writeBookmarkData

TypeScript
static writeBookmarkData(data: ArrayBuffer, url: string): void
Swift declaration
static func writeBookmarkData(_ data: Data, to url: URL) throws

Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.

init · iOS 9.0+

init

TypeScript
static initDataRepresentationRelativeToIsAbsolute(dataRepresentation: ArrayBuffer, base?: (string) | null, isAbsolute?: boolean): (string) | null
Swift declaration
init?(dataRepresentation: Data, relativeTo base: URL?, isAbsolute: Bool = false)

Initializes a newly created URL using the contents of the given data, relative to a base URL. If the data representation isn't a legal URL string as ASCII bytes, the URL object may not behave as expected. This initializer returns `nil` if it can't form a valid URL from the provided data.

get · iOS 9.0+

dataRepresentation

TypeScript
get dataRepresentation(): ArrayBuffer
Swift declaration
var dataRepresentation: Data { get }

The data representation of the URL's relativeString. If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.

get · iOS 16.0+

documentsDirectory

TypeScript
static get documentsDirectory(): string
Swift declaration
static var documentsDirectory: URL { get }

The standard directory for document files. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

get · iOS 16.0+

downloadsDirectory

TypeScript
static get downloadsDirectory(): string
Swift declaration
static var downloadsDirectory: URL { get }

The downloads directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

get · iOS 16.0+

temporaryDirectory

TypeScript
static get temporaryDirectory(): string
Swift declaration
static var temporaryDirectory: URL { get }

The standard directory for temporary files. Complexity: O(1)

method · iOS 8.0+ · Deprecated in iOS 100000.0

appendPathComponent

TypeScript
appendPathComponentIsDirectory(pathComponent: string, isDirectory: boolean): void
Swift declaration
mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool)

Appends a path component to the URL. - parameter pathComponent: The path component to add. - parameter isDirectory: Use `true` if the resulting path is a directory.

method · iOS 8.0+ · Deprecated in iOS 100000.0

appendPathComponent

TypeScript
appendPathComponent(pathComponent: string): void
Swift declaration
mutating func appendPathComponent(_ pathComponent: String)

Appends a path component to the URL. > Note: This function performs a file system operation to determine if > the path component is a directory. If so, it will append a trailing > `/`. If you know in advance that the path component is a directory or > not, then use `func appendingPathComponent(_:isDirectory:)`. New code should use ``URL/append(path:directoryHint:)`` instead of this method. - Parameter pathComponent: The path component to add.

method · iOS 8.0+

appendPathExtension

TypeScript
appendPathExtension(pathExtension: string): void
Swift declaration
mutating func appendPathExtension(_ pathExtension: String)

Appends the given path extension to self. If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing. Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged. - parameter pathExtension: The extension to append.

method · iOS 8.0+

deletePathExtension

TypeScript
deletePathExtension(): void
Swift declaration
mutating func deletePathExtension()

Returns a URL constructed by removing any path extension. If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.

get · iOS 16.0+

applicationDirectory

TypeScript
static get applicationDirectory(): string
Swift declaration
static var applicationDirectory: URL { get }

The standard directory for apps. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

init · iOS 8.0+

init

TypeScript
static initResolvingAliasFileAtOptions(url: string, options?: NSURL_BookmarkResolutionOptions): string
Swift declaration
init(resolvingAliasFileAt url: URL, options: URL.BookmarkResolutionOptions = []) throws

Creates a URL that refers to the location specified by resolving an alias file. If the `url` argument doesn't refer to an alias file (as defined by the ``URLResourceKey/isAliasFileKey`` property), the returned URL is the same as the `url` argument. This method throws an error if the url argument is unreachable, the original file or directory is unknown or unreachable, or the original file or directory is on a volume that the system can't locate or mount. This method doesn't support the ``NSURL/BookmarkResolutionOptions/withSecurityScope`` option.

method · iOS 8.0+

deletingPathExtension

TypeScript
deletingPathExtension(): string
Swift declaration
func deletingPathExtension() -> URL

Returns a URL constructed by removing any path extension. If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.

method · iOS 8.0+

resolveSymlinksInPath

TypeScript
resolveSymlinksInPath(): void
Swift declaration
mutating func resolveSymlinksInPath()

Resolves any symlinks in the path of a file URL. If the `isFileURL` is false, this method does nothing.

init · iOS 8.0+

init

TypeScript
static initResolvingBookmarkDataOptionsRelativeToBookmarkDataIsStale(data: ArrayBuffer, options: NSURL_BookmarkResolutionOptions, url: (string) | null, bookmarkDataIsStale: boolean): { $ret: (string) | null; $out: { "bookmarkDataIsStale": boolean } }
Swift declaration
init?(resolvingBookmarkData data: Data, options: URL.BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws

Initializes a URL that refers to a location specified by resolving bookmark data.

Omit the output parameters from the call. The result contains $ret and $out, with bookmarkDataIsStale inside $out.

init · iOS 8.0+

init

TypeScript
static initResolvingBookmarkDataOptionsRelativeToBookmarkDataIsStale67726(data: ArrayBuffer, options: NSURL_BookmarkResolutionOptions, url: (string) | null, bookmarkDataIsStale: boolean): { $ret: string; $out: { "bookmarkDataIsStale": boolean } }
Swift declaration
init(resolvingBookmarkData data: Data, options: URL.BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws

Creates a URL that refers to a location specified by resolving bookmark data. - Parameters: - data: The bookmark data used to construct a URL. - options: Options taken into account when resolving the bookmark data. - url: The base URL that the bookmark data is relative to. - bookmarkDataIsStale: On return, if `true`, the bookmark data is stale. Your app should create a new bookmark using the returned URL and use it in place of any stored copies of the existing bookmark.

Omit the output parameters from the call. The result contains $ret and $out, with bookmarkDataIsStale inside $out.

get · iOS 16.0+

sharedPublicDirectory

TypeScript
static get sharedPublicDirectory(): string
Swift declaration
static var sharedPublicDirectory: URL { get }

The user’s public sharing directory. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

method · iOS 8.0+ · Deprecated in iOS 100000.0

appendingPathComponent

TypeScript
appendingPathComponentIsDirectory(pathComponent: string, isDirectory: boolean): string
Swift declaration
func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL

Returns a URL constructed by appending the given path component to self. - parameter pathComponent: The path component to add. - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.

method · iOS 8.0+ · Deprecated in iOS 100000.0

appendingPathComponent

TypeScript
appendingPathComponent(pathComponent: string): string
Swift declaration
func appendingPathComponent(_ pathComponent: String) -> URL

Returns a URL constructed by appending the given path component to self. > Note: This function performs a file system operation to determine if > the path component is a directory. If so, it will append a trailing > `/`. If you know in advance that the path component is a directory or > not, then use `func appendingPathComponent(_:isDirectory:)`. New code should use ``URL/appending(path:directoryHint:)`` instead of this method. - Parameter pathComponent: The path component to add.

method · iOS 8.0+

appendingPathExtension

TypeScript
appendingPathExtension(pathExtension: string): string
Swift declaration
func appendingPathExtension(_ pathExtension: String) -> URL

Returns a URL constructed by appending the given path extension to self. If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged. Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged. - parameter pathExtension: The extension to append.

method · iOS 8.0+

deleteLastPathComponent

TypeScript
deleteLastPathComponent(): void
Swift declaration
mutating func deleteLastPathComponent()

Returns a URL constructed by removing the last path component of self. This function may either remove a path component or append `/..`. If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.

method · iOS 8.0+

resolvingSymlinksInPath

TypeScript
resolvingSymlinksInPath(): string
Swift declaration
func resolvingSymlinksInPath() -> URL

Resolves any symlinks in the path of a file URL. If the `isFileURL` is false, this method returns `self`.

method · iOS 8.0+

checkResourceIsReachable

TypeScript
checkResourceIsReachable(): boolean
Swift declaration
func checkResourceIsReachable() throws -> Bool

Returns whether the URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.

get · iOS 8.0+

customPlaygroundQuickLook

TypeScript
get customPlaygroundQuickLook(): SDKHandle
Swift declaration
var customPlaygroundQuickLook: PlaygroundQuickLook { get }

A playground quicklook for the URL.

method · iOS 8.0+

deletingLastPathComponent

TypeScript
deletingLastPathComponent(): string
Swift declaration
func deletingLastPathComponent() -> URL

Returns a URL constructed by removing the last path component of self. This function may either remove a path component or append `/..`. If the URL has an empty path that is not resolved against a base URL (e.g., `http://www.example.com`), then this function will return the URL unchanged.

method · iOS 8.0+

removeCachedResourceValue

TypeScript
removeCachedResourceValue(key: URLResourceKey): void
Swift declaration
mutating func removeCachedResourceValue(forKey key: URLResourceKey)

Removes the cached resource value identified by a given resource value key from the URL object. Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.

method · iOS 8.0+

setTemporaryResourceValue

TypeScript
setTemporaryResourceValue(value: SDKHandle, key: URLResourceKey): void
Swift declaration
@preconcurrency mutating func setTemporaryResourceValue(_ value: any Sendable, forKey key: URLResourceKey)

Sets a temporary resource value on the URL object. Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property. To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.

method · iOS 8.0+

promisedItemResourceValues

TypeScript
promisedItemResourceValues(keys: Array<URLResourceKey>): URLResourceValues
Swift declaration
func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues

Get resource values from URLs of 'promised' items. A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently: NSMetadataQueryUbiquitousDataScope NSMetadataQueryUbiquitousDocumentsScope A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true: You are using a URL that you know came directly from one of the above APIs You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.

get · iOS 16.0+

applicationSupportDirectory

TypeScript
static get applicationSupportDirectory(): string
Swift declaration
static var applicationSupportDirectory: URL { get }

The application support directory for the current user. Complexity: O(n) where n is the number of significant directories specified by `FileManager.SearchPathDirectory`

method · iOS 8.0+

checkPromisedItemIsReachable

TypeScript
checkPromisedItemIsReachable(): boolean
Swift declaration
func checkPromisedItemIsReachable() throws -> Bool

Returns whether the promised item URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.

method · iOS 8.0+

removeAllCachedResourceValues

TypeScript
removeAllCachedResourceValues(): void
Swift declaration
mutating func removeAllCachedResourceValues()

Removes all cached resource values and all temporary resource values from the URL object. This method is currently applicable only to URLs for file system resources.

init · iOS 8.0+

init

TypeScript
static initFileReferenceLiteralResourceName(name: string): string
Swift declaration
init(fileReferenceLiteralResourceName name: String)

Creates a URL from a playground file literal. - Parameter name: The playground file literal name, as a string.

method · iOS 8.0+

withUnsafeFileSystemRepresentation

TypeScript
withUnsafeFileSystemRepresentation(block: ((arg0: (SDKHandle) | null) => unknown)): unknown
Swift declaration
func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType

Passes the URL's path in file system representation to `block`. File system representation is a null-terminated C string with canonical UTF-8 encoding. - note: The pointer is not valid outside the context of the block.

init · iOS 8.0+

init

TypeScript
static initFileURLWithFileSystemRepresentationIsDirectoryRelativeTo(path: SDKHandle, isDirectory: boolean, base?: (string) | null): string
Swift declaration
init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo base: URL?)

Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.

method · iOS 8.0+

stopAccessingSecurityScopedResource

TypeScript
stopAccessingSecurityScopedResource(): void
Swift declaration
func stopAccessingSecurityScopedResource()

Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.

method · iOS 8.0+

startAccessingSecurityScopedResource

TypeScript
startAccessingSecurityScopedResource(): boolean
Swift declaration
func startAccessingSecurityScopedResource() -> Bool

Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).

init · iOS 16.0+

init

TypeScript
static initForInAppropriateForCreate(directory: FileManager_SearchPathDirectory, domain: FileManager_SearchPathDomainMask, url?: (string) | null, shouldCreate?: boolean): string
Swift declaration
init(for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL? = nil, create shouldCreate: Bool = false) throws

Creates a file URL for a common directory in a domain. - Parameters: - directory: The search path for the commonly used directory. - domain: The file system domain to search. Specify only one domain for this parameter. - url: The file URL for determining the location of the returned URL. Only the volume of this parameter is relevant. - shouldCreate: A Boolean value that indicates whether the initializer creates the directory if it doesn't already exist.

method · iOS 16.0+

host

TypeScript
hostPercentEncoded(percentEncoded?: boolean): (string) | null
Swift declaration
func host(percentEncoded: Bool = true) -> String?

Returns the host component of the URL, optionally removing any percent-encoding. The system doesn't allow certain characters in the URL host component, so ``URL`` percent-encodes those characters to create a valid URL. Calling this function with `percentEncoded = false` removes any percent-encoding and returns the unencoded host. If the URL doesn't contain a host component according to [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt), this function returns `nil`. - Parameter percentEncoded: Whether the host should be percent encoded, defaults to `true`. - Returns: The host component of the URL.

get · iOS 8.0+ · Deprecated in iOS 100000.0

host

TypeScript
get host(): (string) | null
Swift declaration
var host: String? { get }

The host component of a URL if the URL conforms to RFC 3986; otherwise, nil. > Note: This function resolves against the base `URL`. New code should use ``URL/host(percentEncoded:)`` instead of this property.

method · iOS 16.0+

path

TypeScript
pathPercentEncoded(percentEncoded?: boolean): string
Swift declaration
func path(percentEncoded: Bool = true) -> String

Returns the path component of the URL, optionally removing any percent-encoding. The system doesn't allow certain characters in the URL path component, so ``URL`` percent-encodes those characters to create a valid URL. Calling this function with `percentEncoded = false` removes any percent-encoding and returns the unencoded path. If the URL's path component is empty, this method returns an empty string. - Note: This function resolves against the base `URL`. - Parameter percentEncoded: Whether the path should be percent encoded, defaults to `true`. - Returns: The path component of the URL.

get · iOS 8.0+ · Deprecated in iOS 100000.0

path

TypeScript
get path(): string
Swift declaration
var path: String { get }

The path component of the URL if the URL conforms to RFC 3986; otherwise, an empty string. > Note: This function resolves against the base `URL`. New code should use ``URL/path(percentEncoded:)`` instead of this property. - Returns: The path, or an empty string if the URL has an empty path.

get · iOS 8.0+

port

TypeScript
get port(): (number) | null
Swift declaration
var port: Int? { get }

The port component of the URL if the URL conforms to RFC 3986; otherwise, nil. > Note: This function resolves against the base `URL`.

method · iOS 16.0+

user

TypeScript
userPercentEncoded(percentEncoded?: boolean): (string) | null
Swift declaration
func user(percentEncoded: Bool = true) -> String?

Returns the user component of the URL, optionally removing any percent-encoding. The system doesn't allow certain characters in the URL user component, so ``URL`` percent-encodes those characters to create a valid URL. Calling this function with `percentEncoded = false` removes any percent-encoding and returns the unencoded user. If the URL doesn't contain a user component according to [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt), this function returns `nil`. - Parameter percentEncoded: Whether the user should be percent encoded, defaults to `true`. - Returns: The user component of the URL.

get · iOS 8.0+ · Deprecated in iOS 100000.0

user

TypeScript
get user(): (string) | null
Swift declaration
var user: String? { get }

The user component of the URL if the URL conforms to RFC 3986; otherwise, nil. > Note: This function resolves against the base `URL`. New code should use ``URL/user(percentEncoded:)`` instead of this property.

get · iOS 15.0+

lines

TypeScript
get lines(): AsyncLineSequence<URL_AsyncBytes>
Swift declaration
var lines: AsyncLineSequence<URL.AsyncBytes> { get }

The URL's resource data, as an asynchronous sequence of lines of text. Use this property with Swift's `for`-`await`-`in` syntax, to read the contents of a URL line-by-line. To wait for the entire resource to load, use the ``URLSession`` method ``URLSession/data(from:delegate:)`` with the `await` keyword.

method · iOS 16.0+

query

TypeScript
queryPercentEncoded(percentEncoded?: boolean): (string) | null
Swift declaration
func query(percentEncoded: Bool = true) -> String?

Returns the query component of the URL, optionally removing any percent-encoding. The system doesn't allow certain characters in the URL query component, so ``URL`` percent-encodes those characters to create a valid URL. Calling this function with `percentEncoded = false` removes any percent-encoding and returns the unencoded query. If the URL doesn't contain a query component according to [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt), this function returns `nil`. - Parameter percentEncoded: Whether the query should be percent encoded, defaults to `true`. - Returns: The query component of the URL.

get · iOS 8.0+ · Deprecated in iOS 100000.0

query

TypeScript
get query(): (string) | null
Swift declaration
var query: String? { get }

The query of the URL if the URL conforms to RFC 3986; otherwise, nil. > Note: This function resolves against the base `URL`. New code should use ``URL/query(percentEncoded:)`` instead of this property.

method · iOS 16.0+

append

TypeScript
appendQueryItems(queryItems: Array<URLQueryItem>): void
Swift declaration
mutating func append(queryItems: [URLQueryItem])

Appends a list of `URLQueryItem` to the receiver. - Parameter queryItems: A list of `URLQueryItem` to append to the receiver.

method · iOS 16.0+

append

TypeScript
appendPathDirectoryHint(path: string, directoryHint?: URL_DirectoryHint): void
Swift declaration
mutating func append<S>(path: S, directoryHint: URL.DirectoryHint = .inferFromPath) where S : StringProtocol

Appends a path to the URL, with a hint for handling directory awareness. This method doesn't percent-encode any path separators (`/`) in the path component before appending the component to the path. If you want this encoding, use ``URL/append(component:directoryHint:)`` instead. - Parameters: - path: The path to add. - directoryHint: A hint to whether this URL will point to a directory. Defaults to ``URL/DirectoryHint/inferFromPath``.

method · iOS 16.0+

append

TypeScript
appendComponentDirectoryHint(component: string, directoryHint?: URL_DirectoryHint): void
Swift declaration
mutating func append<S>(component: S, directoryHint: URL.DirectoryHint = .inferFromPath) where S : StringProtocol

Appends a path component to the receiver. The path component is first percent-encoded before being appended to the receiver. - Parameters: - component: A path component to append to the receiver. - directoryHint: A hint to whether this URL will point to a directory.

get · iOS 8.0+

scheme

TypeScript
get scheme(): (string) | null
Swift declaration
var scheme: String? { get }

The scheme of the URL.

init · iOS 8.0+

init

TypeScript
static initStringRelativeTo(string: string, url?: (string) | null): (string) | null
Swift declaration
init?(string: String, relativeTo url: URL?)

Creates a URL instance from the provided string, relative to another URL. - Parameters: - string: A relative URL location. - url: A URL that provides a base location that the string extends. > Important: For apps linked on or after iOS 17 and aligned OS versions, > ``URL`` parsing has updated from the obsolete RFC 1738/1808 parsing to > the same [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) parsing as > ``URLComponents``. This unifies the parsing behaviors of the `URL` and > `URLComponents` APIs. Now, `URL` automatically percent- and > IDNA-encodes invalid characters to help create a valid URL. This initializer returns `nil` if the string doesn't represent a valid URL even after encoding invalid characters. To check if a URL string is strictly valid according to the RFC, use the new ``URL/init(string:encodingInvalidCharacters:)`` initializer and pass `encodingInvalidCharacters: false`. This leaves all characters as they are and returns `nil` if the URL string is explicitly invalid.

init · iOS 17.0+

init

TypeScript
static initStringEncodingInvalidCharacters(string: string, encodingInvalidCharacters: boolean): (string) | null
Swift declaration
init?(string: String, encodingInvalidCharacters: Bool)

Creates a URL instance from the provided string, optionally IDNA- and percent-encoding any invalid characters. - Parameters: - string: A URL location. - encodingInvalidCharacters: A Boolean value that indicates whether the initializer attempts to encode any invalid characters in `string`. If `encodingInvalidCharacters` is `true`, this initializer tries to encode the string to create a valid URL. If the URL string is still invalid after encoding, the initializer returns `nil`. If `encodingInvalidCharacters` is `false`, and the URL string is invalid according to RFC 3986, `nil` is returned.

init · iOS 8.0+

init

TypeScript
static initString(string: string): (string) | null
Swift declaration
init?(string: String)

Creates a URL instance from the provided string. - Parameter string: A URL location. > Important: For apps linked on or after iOS 17 and aligned OS versions, > ``URL`` parsing has updated from the obsolete RFC 1738/1808 parsing to > the same [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt) parsing as > ``URLComponents``. This unifies the parsing behaviors of the `URL` and > `URLComponents` APIs. Now, `URL` automatically percent- and > IDNA-encodes invalid characters to help create a valid URL. This initializer returns `nil` if the string doesn't represent a valid URL even after encoding invalid characters. To check if a URL string is strictly valid according to the RFC, use the new ``URL/init(string:encodingInvalidCharacters:)`` initializer and pass `encodingInvalidCharacters: false`. This leaves all characters as they are and returns `nil` if the URL string is explicitly invalid.

init · iOS 16.0+

init

TypeScript
static initFilePathDirectoryHintRelativeTo(path: string, directoryHint?: URL_DirectoryHint, base?: (string) | null): string
Swift declaration
init(filePath path: String, directoryHint: URL.DirectoryHint = .inferFromPath, relativeTo base: URL? = nil)

Creates a file URL that references a path you specify as a string. - Parameters: - path: The location in the file system, as a string. - directoryHint: A hint to the initializer to indicate whether the path is a directory, or to instruct the initializer to make this determination. - base: A URL that provides a file system location that the path extends. If an empty string is used for the path, the system interprets it as ".".

init · iOS 16.0+

init

TypeScript
static initFilePathDirectoryHint(path: _System_FilePath, directoryHint?: URL_DirectoryHint): (string) | null
Swift declaration
init?(filePath path: FilePath, directoryHint: URL.DirectoryHint = .inferFromPath)

Creates a URL from a file path by by copying and validating its UTF-8 contents. This initializer does not try to repair ill-formed UTF-8 code unit sequences. If any are found, the result of the initializer is `nil`.

method · iOS 16.0+

fragment

TypeScript
fragmentPercentEncoded(percentEncoded?: boolean): (string) | null
Swift declaration
func fragment(percentEncoded: Bool = true) -> String?

Returns the fragment component of the URL, optionally removing any percent-encoding. The system doesn't allow certain characters in the URL fragment component, so ``URL`` percent-encodes those characters to create a valid URL. Calling this function with `percentEncoded = false` removes any percent-encoding and returns the unencoded fragment. If the URL doesn't contain a fragment component according to [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt), this function returns `nil`. - Parameter percentEncoded: Whether the fragment should be percent encoded, defaults to `true`. - Returns: The fragment component of the URL.

get · iOS 8.0+ · Deprecated in iOS 100000.0

fragment

TypeScript
get fragment(): (string) | null
Swift declaration
var fragment: String? { get }

The fragment component of the URL if the URL conforms to RFC 3986; otherwise, nil. > Note: This function resolves against the base `URL`. New code should use ``URL/fragment(percentEncoded:)`` instead of this property.

method · iOS 16.0+

password

TypeScript
passwordPercentEncoded(percentEncoded?: boolean): (string) | null
Swift declaration
func password(percentEncoded: Bool = true) -> String?

Returns the password component of the URL, optionally removing any percent-encoding. The system doesn't allow certain characters in the URL password component, so ``URL`` percent-encodes those characters to create a valid URL. Calling this function with `percentEncoded = false` removes any percent-encoding and returns the unencoded password. If the URL doesn't contain a password component according to [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt), this function returns `nil`. - Parameter percentEncoded: Whether the password should be percent encoded, defaults to `true`. - Returns: The password component of the URL.

get · iOS 8.0+ · Deprecated in iOS 100000.0

password

TypeScript
get password(): (string) | null
Swift declaration
var password: String? { get }

The password component of the URL if the URL conforms to RFC 3986; otherwise, nil. > Note: This function resolves against the base `URL`. New code should use ``URL/password(percentEncoded:)`` instead of this property.

init · iOS 16.0+

init

TypeScript
static initResource(resource: URLResource): (string) | null
Swift declaration
init?(resource: URLResource)

Creates a URL from a resource. Use this initializer to resolve `URLResource` instances, possibly received from other processes, into `URL` instances. - Parameter resource: A `URLResource` that provides a reference to a resource in a given bundle.

init · iOS 26.0+

init

TypeScript
static initTemplateVariables(template: URL_Template, variables: NativeMap<URL_Template_VariableName, URL_Template_Value>): (string) | null
Swift declaration
init?(template: URL.Template, variables: [URL.Template.VariableName : URL.Template.Value])

Creates a new `URL` by expanding the RFC 6570 template and variables. This will fail if variable expansion does not produce a valid, well-formed URL. All text will be converted to NFC (Unicode Normalization Form C) and UTF-8 before being percent-encoded if needed. - Parameters: - template: The RFC 6570 template to be expanded. - variables: Variables to expand in the template.

method · iOS 16.0+

appending

TypeScript
appendingQueryItems(queryItems: Array<URLQueryItem>): string
Swift declaration
func appending(queryItems: [URLQueryItem]) -> URL

Returns a URL constructed by appending the given list of `URLQueryItem` to self. - Parameter queryItems: A list of `URLQueryItem` to append to the receiver.

method · iOS 16.0+

appending

TypeScript
appendingPathDirectoryHint(path: string, directoryHint?: URL_DirectoryHint): string
Swift declaration
func appending<S>(path: S, directoryHint: URL.DirectoryHint = .inferFromPath) -> URL where S : StringProtocol

Returns a URL constructed by appending the given path to self. This method doesn't percent-encode any path separators (`/`) in the path component before appending the component to the path. If you want this encoding, use ``URL/appending(component:directoryHint:)`` instead. - Parameters: - path: The path to add. - directoryHint: A hint to whether this URL will point to a directory.

method · iOS 16.0+

appending

TypeScript
appendingComponentDirectoryHint(component: string, directoryHint?: URL_DirectoryHint): string
Swift declaration
func appending<S>(component: S, directoryHint: URL.DirectoryHint = .inferFromPath) -> URL where S : StringProtocol

Returns a URL constructed by appending the given path component to self. The path component is first percent-encoded before being appended to the receiver. - Parameters: - component: A path component to append to the receiver. - directoryHint: A hint to whether this URL will point to a directory. - Returns: The new URL

method · iOS 16.0+

formatted

TypeScript
formatted(): string
Swift declaration
func formatted() -> String

Formats the URL using a default format style. Use this method to create a string representation of a URL using the default ``URL/FormatStyle`` configuration. The default style creates a string with the scheme, host, and path, but not the port or query. To customize formatting of the URL, use ``URL/formatted(_:)``, passing in a customized ``FormatStyle``. - Returns: A string representation of the URL, formatted according to the default format style.

init · iOS 14.0+ · Deprecated in iOS 16.0

init

TypeScript
static initIsDirectory(path: _System_FilePath, isDirectory: boolean): (string) | null
Swift declaration
init?(_ path: FilePath, isDirectory: Bool)

Creates a URL from a file path by by copying and validating its UTF-8 contents. This initializer does not try to repair ill-formed UTF-8 code unit sequences. If any are found, the result of the initializer is `nil`.

init · iOS 14.0+ · Deprecated in iOS 16.0

init

TypeScript
static init(path: _System_FilePath): (string) | null
Swift declaration
init?(_ path: FilePath)

Creates a URL from a file path by by copying and validating its UTF-8 contents. This initializer does not try to repair ill-formed UTF-8 code unit sequences. If any are found, the result of the initializer is `nil`.

Skipped declarations

4 declarations were excluded from these bindings. Each reason comes from the generator or the iOS SDK compiler.

URL.appending(components:directoryHint:)

A variable number of Swift arguments is not supported.

URL.append(components:directoryHint:)

A variable number of Swift arguments is not supported.

URL.init(_:strategy:)

This declaration needs Swift generic type arguments. (no canonical witness for T.ParseInput)

URL.formatted(_:)

This declaration needs Swift generic type arguments. (no canonical witness for F)

All Foundation types →