Validate iOS download types on a cloud Mac

Validate iOS download types on a cloud Mac

Validate iOS download types on a cloud Mac

An iOS download API reports success, but the preview screen cannot open the attachment. Sometimes the response is an error page returned after a login session expires. Sometimes the server labels everything as generic binary data. In other cases, only half the file arrives. To reproduce these issues on a cloud Mac, you do not need to connect to the real service first. Separate three questions—what the response declares, what its bytes resemble, and whether it can be fully parsed—then build three layers of validation with fixed fixtures before wiring them into the download flow.

Define the accepted formats first

Assume the attachment endpoint accepts only PNG, JPEG, and PDF files. The rules should come from a business-defined allowlist, not guesses based on filenames. A filename can be shown to the user, but it must not determine which parser handles the file or be used directly to construct a destination path.

Validate in this order: check that the HTTP status meets the API contract, enforce a limit on the bytes actually received, compare the response MIME type with the file signature, and finally run format-specific parsing. Content-Length is only one signal for rejecting a response early. A missing or understated value cannot replace a cumulative byte limit.

A matching signature only means “this looks like that format.” It does not prove completeness, much less safety. A file containing nothing but a PNG signature still cannot be displayed.

If an API explicitly returns generic binary data, you can configure an exception for that endpoint. Do not extend the same leniency to every download. The implementation below uses strict mode: a missing MIME type or a conflicting declaration causes rejection.

Isolate type detection in a pure function

Create type-check.swift in the remote macOS terminal and save the following content. The function accepts only the leading bytes and a MIME type. It makes no network requests and does not access user directories, making it easy to move into the app’s test target later. The fixtures in this code test classification rules only; they are not valid images or documents.

import Foundation

enum FileKind: String {
    case png, jpeg, pdf

    var mime: String {
        switch self {
        case .png: return "image/png"
        case .jpeg: return "image/jpeg"
        case .pdf: return "application/pdf"
        }
    }
}

enum TypeFailure: Error {
    case unknownHeader
    case missingMIME
    case conflictingMIME
}

func classify(
    prefix: Data,
    declaredMIME: String?
) throws -> FileKind {
    let bytes = Array(prefix.prefix(8))
    let kind: FileKind

    if bytes.starts(with: [137, 80, 78, 71, 13, 10, 26, 10]) {
        kind = .png
    } else if bytes.starts(with: [255, 216, 255]) {
        kind = .jpeg
    } else if bytes.starts(with: Array("%PDF-".utf8)) {
        kind = .pdf
    } else {
        throw TypeFailure.unknownHeader
    }

    guard let declaredMIME else {
        throw TypeFailure.missingMIME
    }

    let mime = declaredMIME
        .split(separator: ";", omittingEmptySubsequences: false)[0]
        .trimmingCharacters(in: .whitespacesAndNewlines)
        .lowercased()

    guard mime == kind.mime else {
        throw TypeFailure.conflictingMIME
    }
    return kind
}

struct Fixture {
    let head: [UInt8]
    let mime: String?
    let expected: FileKind?
}

let fixtures: [Fixture] = [
    .init(
        head: [137, 80, 78, 71, 13, 10, 26, 10],
        mime: "IMAGE/PNG; charset=binary",
        expected: .png
    ),
    .init(head: [255, 216, 255], mime: "image/jpeg", expected: .jpeg),
    .init(
        head: Array("%PDF-1.7".utf8),
        mime: "application/pdf",
        expected: .pdf
    ),
    .init(
        head: Array("<html>error".utf8),
        mime: "application/pdf",
        expected: nil
    ),
    .init(head: [137, 80, 78], mime: "image/png", expected: nil),
    .init(head: [255, 216, 255], mime: "image/png", expected: nil),
    .init(head: [255, 216, 255], mime: nil, expected: nil)
]

for (index, fixture) in fixtures.enumerated() {
    let actual = try? classify(
        prefix: Data(fixture.head),
        declaredMIME: fixture.mime
    )
    guard actual == fixture.expected else {
        fatalError("Fixture mismatch at index \(index)")
    }
}

Run xcrun swift type-check.swift. It exits silently if every result matches, or returns a nonzero exit code if an assertion fails. The header strings are used directly here to cover case differences and parameters. If the app reads an already normalized MIME type, retain the original response headers for troubleshooting, but do not log authentication fields.

Do not load the entire file into memory when integrating downloads

When using a download task, first check the task error, response status, and whether the temporary file exists. Then use FileHandle to read at most eight bytes and pass them to the classification function. Close the handle with defer. Do not use Data(contentsOf:) to load the entire file just to read its signature. With a large attachment, that turns a simple check into a memory spike.

For streamed responses, accumulate the first eight bytes rather than assuming the first callback contains the complete signature. Callback chunk boundaries have no relationship to file-format boundaries. If there is not enough data to classify the file, keep waiting until all eight bytes arrive or the transfer ends, then make the decision.

Promptly move the temporary file supplied by the download task into an app-controlled staging directory. Generate an internal filename, and move the file to its final location only after validation passes. Clean up the staged file if any step fails. A user-supplied name should be used only as a sanitized display field.

Add a second set of fixtures for full parsing

After an image passes type detection, use ImageIO to create an image source and actually produce an image. Being able to read dimensions or create an image source does not guarantee that decoding will succeed. Limit width, height, total pixel count, and frame count before decoding the required frames, so that a small compressed file cannot expand into an enormous in-memory object.

For PDFs, use PDFKit to attempt document creation, then check the page count, encryption status, and the pages the app needs to access. If the application needs to generate a preview, actually render the target page. Successfully creating a document object does not mean every page will display correctly.

Prepare real, valid files alongside copies containing only the file header, copies with their ends truncated, and copies with bytes modified in the middle. Not every truncated fixture will necessarily be rejected by the underlying parser: some parsers tolerate damage. Tests should therefore assert whether the operations required by the app can be completed, rather than assume that every byte change must cause failure.

Report failures in a way that supports diagnosis

Once the checks are integrated into the project’s test target, report transfer failures, unknown formats, conflicting declarations, quota violations, and parsing failures separately. Do not collapse them all into “corrupt file,” or backend MIME configuration errors will become indistinguishable from client-side decoding problems.

For each regression run, retain the fixture ID, actual byte count, normalized MIME type, candidate file type, and processing stage. Prefer artificially generated fixtures with no sensitive content. If a failed attachment contains business data, do not automatically upload it with the test report.

Finish by checking three things: error pages never reach the previewer, truncated fixtures are not treated as files whose completeness has been verified, and failure paths leave no attachment in the final location. Use the cloud Mac to run fixed fixtures and simulator flows; memory behavior with large files on a physical device still requires separate validation. Record the two separately so you know exactly what this validation gate proves.

Frequently asked questions

Should the app silently fix a MIME and signature mismatch?

Reject it by default and record the mismatch. If an endpoint intentionally returns generic binary data, scope the exception to that endpoint and still require signature checks and full parsing.

Does a matching signature prove that a file is intact?

No. A truncated file can retain its signature. Images need complete decoding checks; PDFs need parsing and the page checks required by the application.

Let your project decide which Mac to rent

Need native builds or simulator testing? Rent an Apple Silicon dedicated physical Mac to validate your project. If you develop full-time and work from one location, buying may also be worth comparing. Rent by the day for flexibility, then consider a monthly or quarterly plan for ongoing use.

Rent a Remote Mac

Next, choose a plan for your project stage

Compare Mac models, rental periods, and access options before deciding whether to rent.