Skip to content

Should swifter return content-length when using shareFilesFromDirectory to share files? #380

@nichbar

Description

@nichbar

Lately, I've been using swifter on an iOS app to create a local http server for installing apps that is signed with enterprise certificate within app. (Here's the demo)

server.listenAddressIPv4 = "127.0.0.1"
server["/:path"] = shareFilesFromDirectory(downloadFilePath)
try server.start(8090, forceIPv4: true)

Everything's fine by using the code pasted above, until i try to install an app which size is over 1 gigabyte.

In this circumstance, iOS will stuck like 40 sec before it starts to download file that is shared by swifter.

After some dig in, i found that iOS require header content-length from http response to start download immediately.

Then i change shareFilesFromDirectory like this (just for test)

public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String] = ["index.html", "default.html"]) -> ((HttpRequest) -> HttpResponse) {
    return { r in
        guard let fileRelativePath = r.params.first else {
            return .notFound
        }
        if fileRelativePath.value.isEmpty {
            for path in defaults {
                if let file = try? (directoryPath + String.pathSeparator + path).openForReading() {
                    return .raw(200, "OK", [:], { writer in
                        try? writer.write(file)
                        file.close()
                    })
                }
            }
        }
        if let file = try? (directoryPath + String.pathSeparator + fileRelativePath.value).openForReading() {
            let mimeType = fileRelativePath.value.mimeType();
            
            let filePath = directoryPath + String.pathSeparator + fileRelativePath.value
            var fileSize : UInt64 = 0

            let attr = try FileManager.default.attributesOfItem(atPath: filePath)
            fileSize = attr[FileAttributeKey.size] as! UInt64

            let dict = attr as NSDictionary
            fileSize = dict.fileSize()
            
            return .raw(200, "OK", ["Content-Type": mimeType, "Content-Length": String(fileSize)], { writer in
                try? writer.write(file)
                file.close()
            })
        }
        return .notFound
    }
}

Returning Content-Length solve my problem.

So i wonder shall swifter return content-length when using shareFilesFromDirectory to share files?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions