A downloaded report looks fine in the list, but its filename turns into garbled text when shared. Another report with the same name overwrites an older file. The problem usually lies not in the download itself, but in treating the name suggested by the response header as a local path. If you develop on Windows only, you can run a standalone Swift sample on a cloud Mac first, then integrate the same checks into your iOS download completion callback without waiting for a build of the entire UI.
Define the boundaries first
Split the process into three layers: parsing response header parameters, decoding the suggested name, and generating the local storage path. Each layer should report success or failure independently. Do not roll everything into a single “fix filename” function.
filename is a regular parameter; filename* can include a character set, a language tag, and percent-encoded data. When both are present and the extended parameter is valid, prefer the extended parameter. If the extended parameter is invalid, this article’s policy is to reject the suggested name and use an application-generated display name instead, rather than silently trying another interpretation.
The server suggests a name; it does not authorize a path. Passing filename validation does not mean the file’s contents are trustworthy or safe to execute.
Do not simply split the entire response header on semicolons. Quoted parameter values can contain semicolons, and escaped quotation marks also need handling. Parameter names are case-insensitive; duplicate parameters should be reported as ambiguous. The code below accepts a filename* value already extracted by a parser. It does not parse the full response header.
Decode strictly
An extended value looks like UTF-8''report%20one.pdf. First separate the character set and language fields, then convert the percent-encoded sequences to bytes, and finally decode those bytes strictly as UTF-8. Leave plus signs unchanged: the form-encoding rule that converts a plus sign to a space does not apply here.
Create FilenameCheck.swift on the cloud Mac and add the following code. A working Swift toolchain is required; check it with xcrun swift --version before running the sample.
import Foundation
enum NameError: Error {
case malformed
case unsafe
}
func decodeExtended(_ raw: String) throws -> String {
let parts = raw.split(
separator: "'", maxSplits: 2,
omittingEmptySubsequences: false
)
guard parts.count == 3,
parts[0].lowercased() == "utf-8" else {
throw NameError.malformed
}
let source = Array(parts[2].utf8)
let allowed = Set(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$&+-.^_`|~".utf8
)
var bytes: [UInt8] = []
var index = 0
while index < source.count {
if source[index] == 37 {
guard index + 2 < source.count else {
throw NameError.malformed
}
let pair = source[(index + 1)...(index + 2)]
guard pair.allSatisfy({
(48...57).contains($0)
|| (65...70).contains($0)
|| (97...102).contains($0)
}),
let value = UInt8(
String(decoding: pair, as: UTF8.self), radix: 16
) else {
throw NameError.malformed
}
bytes.append(value)
index += 3
} else {
guard allowed.contains(source[index]) else {
throw NameError.malformed
}
bytes.append(source[index])
index += 1
}
}
guard let result = String(bytes: bytes, encoding: .utf8) else {
throw NameError.malformed
}
return result
}
func checkedName(_ input: String) throws -> String {
let name = input.precomposedStringWithCanonicalMapping
guard !name.isEmpty,
name != ".", name != "..",
!name.hasPrefix("."),
!name.hasSuffix("."),
name == name.trimmingCharacters(in: .whitespacesAndNewlines),
name.utf8.count <= 180 else {
throw NameError.unsafe
}
for scalar in name.unicodeScalars {
let value = scalar.value
guard !CharacterSet.controlCharacters.contains(scalar),
!"/\\:".unicodeScalars.contains(scalar),
!(0x202A...0x202E).contains(value),
!(0x2066...0x2069).contains(value) else {
throw NameError.unsafe
}
}
return name
}
let valid = [
("UTF-8''report%20one.pdf", "report one.pdf"),
("utf-8'zh'%E6%8A%A5%E5%91%8A.pdf", "报告.pdf"),
("UTF-8''a+b.txt", "a+b.txt")
]
for (raw, expected) in valid {
let actual = try checkedName(decodeExtended(raw))
precondition(actual == expected)
}
let rejected = [
"UTF-8''bad%",
"UTF-8''%FF.txt",
"UTF-8''..%2Fsecret",
"UTF-8''a%5Cb.txt",
"UTF-8''a%00.txt",
"UTF-8''%E2%80%AEtxt.exe"
]
for raw in rejected {
var failed = false
do {
_ = try checkedName(decodeExtended(raw))
} catch {
failed = true
}
precondition(failed)
}
Run xcrun swift FilenameCheck.swift. If all checks pass, there is no output. A failed assertion or an uncaught error causes the process to fail. The 180-byte limit here is an application policy, not a filesystem limit. Limiting bytes accounts for the fact that Chinese and English names with the same character count can occupy different amounts of space.
Do not decode again
Add %252F to the sample. Decoding it once produces the literal text %2F, which is not a path separator and can remain in a display name. A second round of percent-decoding would turn it into a slash, invalidating the previous layer’s conclusion.
Make the type semantics explicit in application interfaces: raw parameters may only enter the decoder, and validated names may only enter the presentation layer. Export, sharing, and retry modules must not decode names again on their own. A regular filename must not be processed using extended-parameter rules merely because it contains a percent sign.
Unicode normalization must likewise happen only at the designated boundary. The code normalizes to canonical composed form, but does not treat visually similar characters as identical. Bidirectional control characters are rejected to prevent file extensions from being visually reordered in the UI.
Use separate storage keys
When writing the file to disk, use an application-generated UUID as the storage key and keep the original name in metadata. If a file extension is needed for previews, derive it from a validated content-type policy rather than inheriting it directly from the suggested name.
Move the temporary download file into a private staging directory belonging to the app first. Only move it into the final directory after checking its type, length, and contents. Creating the destination file must prohibit overwriting. A preliminary existence check is not enough, because there is a race between checking and writing.
Concurrent downloads with the same name should produce two distinct storage keys and two independent metadata records. If content deduplication is a product requirement, handle it separately using a content digest. Identical names do not imply identical contents.
Complete the acceptance tests
Move the pure-function tests into the project’s test target and add four groups of integration checks:
- Input boundaries: empty names, empty language tags, mixed-case character set labels, lone percent signs, and excessively long names.
- Header boundaries: semicolons inside quoted values, escaped quotation marks, duplicate parameters, and unknown character sets.
- Storage boundaries: two downloads with the same name complete concurrently, while the bytes of the existing file remain unchanged.
- Failure boundaries: files that fail validation never enter the final directory, and staging files are cleaned up according to the task that owns them.
Use a separate temporary directory for each test and delete that directory afterward. Do not clear a shared download directory. Failure logs should contain only the sample ID, rejection stage, and error category, keeping real download names out of logs.
Finally, run through downloading, restarting the app, displaying the list, and sharing in the simulator. The acceptance criterion is not “it seems to open.” It is that the same input is decoded only once, a name is never treated as a path, and no failure can overwrite an existing file.
Frequently asked questions
Can suggestedFilename be used directly as a storage path?
No. Validate it as a single filename and use an application-generated storage key for the actual file. Keep the suggested name as display metadata.
Should a plus sign in filename* become a space?
No. A plus sign is literal in this parameter. Decode valid percent-encoded bytes once; do not apply form-encoding rules.
Move your project to a cloud Mac
Rent a dedicated physical node and access the macOS desktop in your browser. Choose your configuration and billing period, then build your project in Xcode.