Sample code for 30+ languages & platforms
Swift

REST Download Binary File to Memory

See more REST Examples

Download a binary file to a Chilkat BinData object.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let rest = CkoRest()!

    // We're going to download a sample MS-Word doc file.
    // The URLs of our MS-Word sample documents are:

    // https://www.chilkatdownload.com/sample_data/sample.doc
    // https://www.chilkatdownload.com/sample_data/sample.docx

    var pathPartOfUrl: String? = "/sample_data/sample.doc"
    var domain: String? = "chilkatdownload.com"

    var bTls: Bool = true
    var port: Int = 443
    var bAutoReconnect: Bool = true
    success = rest.connect(hostname: domain, port: port, tls: bTls, autoReconnect: bAutoReconnect)
    if success != true {
        print("\(rest.lastErrorText!)")
        return
    }

    let bd = CkoBinData()!
    success = rest.fullRequestNoBodyBd(httpVerb: "GET", uriPath: pathPartOfUrl, binData: bd)
    if success != true {
        print("\(rest.lastErrorText!)")
        return
    }

    // A 200 response is expected for actual success.
    // If we don't get a 200 response, then the response body was not actually
    // the file data, but it was text containing error information.
    if rest.responseStatusCode.intValue != 200 {
        let sbErrorText = CkoStringBuilder()!
        sbErrorText.appendBd(binData: bd, charset: "utf-8", offset: 0, numBytes: 0)
        print("\(sbErrorText.getAsString()!)")
        print("-- Failed.")
        return
    }

    // Save to a local file.
    // Change the file path based on your operating system or needs...
    success = bd.writeFile(path: "c:/temp/qa_output/sample.doc")
    if success != true {
        print("Failed to save to local file.")
        return
    }

    print("REST Download of MS-Word File was successful.")

}