2.3 · URL, URLComponents, Data, FileManager
A URL names a resource, Data holds its bytes, and FileManager moves them to and from disk. Most bugs here are about strings pretending to be URLs, and paths pretending to be strings.
Mental model. Never build a URL by pasting strings. Let URL and URLComponents own the parsing and the percent-encoding, and let the file system tell you what is possible by trying it.
URLs
Parsing, building, and the difference between a web address and a file path.
- What is a URL in Foundation, and what does URL(string:) accept?
URL is a value type that holds a parsed address: scheme, host, port, path, query and fragment. It does not fetch anything; it is just a structured name.… - What is the difference between a file URL and a web URL, and URL(fileURLWithPath:) and URL(string:)?
URL(fileURLWithPath:) takes a file system path, adds the file:// scheme, resolves a relative path against the current directory, and escapes characters as… - How do you build, change and resolve URL paths safely?
Edit paths with the URL APIs, not string slicing: appendingPathComponent(_:) (or appending(path:)) adds a segment and percent-encodes it… - Why use URLComponents and URLQueryItem, and what do they still not encode for you?
URLComponents lets you set scheme, host, path and queryItems separately and then ask for url. It percent-encodes each part for its own context, so you avoid…
Data
Bytes, text, and slices that keep their indices.
- What is Data, and how do you convert it to and from text?
Data is a value type holding a run of bytes, with copy-on-write storage. It is the currency of file, network and crypto APIs. Convert text with…
Files
Where files may live, and how to read and write them safely.
- Where should an iOS app put files: Documents, Application Support, Caches or tmp?
Pick by two questions: can I rebuild it? and does the user own it? Documents holds user-created content and is backed up. Application Support holds data the… - How do you read and write files safely, and why is fileExists-then-act a bug?
Write with data.write(to:options: .atomic): it writes a temporary file and renames it into place, so a crash never leaves a half-written file. Read small files…
More in Foundation & stdlib
- 2.1 · Collections, indexing, Sequence and lazy
- 2.2 · Date, Calendar, Locale, TimeZone, FormatStyle
- 2.4 · NotificationCenter, KVO and Operation
- 2.5 · JSON coder options, property lists, UserDefaults
- 2.6 · Bundle, resources, localization tables
- 2.7 · NSCache and locks
- 2.8 · Attributed strings, scanners, number formatters
- 2.9 · Bridging to Objective-C Foundation types