Sample code for 30+ languages & platforms
Swift

eBay -- Download Data using FileTransferService

See more eBay Examples

Demonstrates how to download a data file using the eBay File Transfer API.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    // Use a previously obtained access token.  The token should look something like this:
    // "AgAAAA**AQA ..."
    var accessToken: String? = "EBAY_ACCESS_TOKEN"

    let http = CkoHttp()!

    let req = CkoHttpRequest()!

    req.httpVerb = "POST"
    req.path = "/FileTransferService"
    req.contentType = "application/xml"

    // Build the XML body for the request.
    let xml = CkoXml()!
    xml.tag = "downloadFileRequest"
    xml.addAttribute(name: "xmlns", value: "http://www.ebay.com/marketplace/services")
    xml.updateChildContent(tagPath: "taskReferenceId", value: "50013004806")
    xml.updateChildContent(tagPath: "fileReferenceId", value: "50015579016")

    req.loadBody(fromString: xml.getXml(), charset: "utf-8")

    // The XML body looks like this:

    // 	<?xml version="1.0" encoding="UTF-8"?>
    // 	<downloadFileRequest xmlns="http://www.ebay.com/marketplace/services">
    // 	<taskReferenceId>50013004806</taskReferenceId>
    // 	<fileReferenceId>50015579016</fileReferenceId>
    // 	</downloadFileRequest>

    req.addHeader(name: "X-EBAY-SOA-OPERATION-NAME", value: "downloadFile")
    req.addHeader(name: "X-EBAY-SOA-SECURITY-TOKEN", value: accessToken)

    let resp = CkoHttpResponse()!
    success = http.httpSReq(domain: "storage.sandbox.ebay.com", port: 443, ssl: true, request: req, response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    var statusCode: Int = resp.statusCode.intValue
    print("Response status code = \(statusCode)")

    let responseBody = CkoBinData()!
    resp.getBodyBd(binData: responseBody)

    // We can save the response body to a file for examination if we get an unanticipated response.  
    // (It's binary, so it won't open well in a text editor.)
    responseBody.writeFile(path: "qa_output/response.mime")

    if statusCode != 200 {
        print("Failed.")
        return
    }

    // The response body looks like this:

    // 	--MIMEBoundaryurn_uuid_2B668636C1E17A4D4114925305818684241
    // 	Content-Type: application/xop+xml; charset=utf-8; type="text/xml"
    // 	Content-Transfer-Encoding: binary
    // 	Content-ID: <0.urn:uuid:2B668636C1E17A4D4114925305818684242>
    // 
    // 	<?xml version='1.0' encoding='UTF-8'?>
    // 	<downloadFileResponse xmlns="http://www.ebay.com/marketplace/services">
    // 	<ack>Success</ack>
    // 	<version>1.1.0</version>
    // 	<timestamp>2017-04-18T15:49:41.868Z</timestamp>
    // 	<fileAttachment>
    // 	    <Size>587</Size>
    // 	    <Data>
    //                 <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:urn:uuid:A37C3C73E994C267F11492530585522"/>
    // 	    </Data>
    // 	</fileAttachment>
    // 	</downloadFileResponse>
    // 	--MIMEBoundaryurn_uuid_2B668636C1E17A4D4114925305818684241
    // 	Content-Type: application/zip
    // 	Content-Transfer-Encoding: binary
    // 	Content-ID: <urn:uuid:A37C3C73E994C267F11492530585522>
    // 
    // 	<the binary bytes of the zip start here...>
    // 

    // Load the binary response into a MIME object.
    let mime = CkoMime()!
    success = mime.loadBd(bindat: responseBody)
    if success == false {
        print("\(mime.lastErrorText!)")
        return
    }

    // Make sure we have 2 sub-parts.  The 1st sub-part is the XML response, the 2nd sub-part
    // is the zip containing the data.

    // Note: The 2nd sub-part can be a "zip" or "gzip".  These are two different file formats.
    // A zip is indicated with a Content-Type header equal to "application/zip",
    // whereas a gzip is indicated with a Content-Type header equal to "application/x-gzip"
    if mime.numParts.intValue != 2 {
        print("Expected the MIME to have 2 parts.")
        print("NumParts = \(mime.numParts.intValue)")
        print("Failed.")
        return
    }

    // Get the XML from the 1st MIME sub-part.

    let part0 = CkoMime()!
    success = mime.part(at: 0, subPart: part0)
    if success == false {
        print("\(mime.lastErrorText!)")
        return
    }

    var downloadResponseXml: String? = part0.getBodyDecoded()
    let xmlResp = CkoXml()!
    xmlResp.load(xmlData: downloadResponseXml)
    print("Download Response XML:")
    print("\(xmlResp.getXml()!)")

    print("----")

    // Now get the zip from the second part (index=1), unzip, and examine..

    let part1 = CkoMime()!
    success = mime.part(at: 1, subPart: part1)
    if success == false {
        print("\(mime.lastErrorText!)")
        return
    }

    let zipData = CkoBinData()!
    part1.getBodyBd(binDat: zipData)

    // Check to see if we have a zip or gzip.
    let sbContentType = CkoStringBuilder()!
    sbContentType.append(value: part1.contentType)

    let xmlFromZip = CkoXml()!

    if sbContentType.contains(str: "gzip", caseSensitive: false) == true {
        // This is a gzip compressed file.
        let gzip = CkoGzip()!

        // in-place uncompress the data.
        // Note: The UncompressBd method was added in Chilkat v9.5.0.67
        success = gzip.uncompressBd(binDat: zipData)
        if success == false {
            print("\(gzip.lastErrorText!)")
            return
        }

        xmlFromZip.load(xmlData: zipData.getString(charset: "utf-8"))

    }
    else {
        // This is a zip archive.

        // Load the body into a Zip object.
        let zip = CkoZip()!
        success = zip.openBd(binData: zipData)
        if success == false {
            print("\(zip.lastErrorText!)")
            return
        }

        // Save the .zip to a file (so we can examine it for debugging if something is not as expected)
        zipData.writeFile(path: "qa_output/ebay_data.zip")

        // The zip should contain a single XML file.
        if zip.numEntries.intValue != 1 {
            print("Expected the .zip to have 1 entry.")
            print("NumEntries = \(zip.numEntries.intValue)")
            print("Failed.")
            return
        }

        let entry = CkoZipEntry()!
        success = zip.entry(at: 0, entry: entry)
        if success == false {
            print("\(zip.lastErrorText!)")
            return
        }

        xmlFromZip.load(xmlData: entry.unzip(toString: 0, srcCharset: "utf-8"))
    }

    print("XML contained in the zip:")
    print("\(xmlFromZip.getXml()!)")
    print("----")

    print("Success.")

}