Sample code for 30+ languages & platforms
Swift

UPS Tracking API

See more HTTP Misc Examples

Demonstrates making a call to the UPS tracking REST API. Parses the tracking response and extracts the base64 signature image to a gif file.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    let http = CkoHttp()!

    // This is the testing endpoint for the tracking API:
    var url: String? = "https://wwwcie.ups.com/rest/Track"

    // Send an HTTP request with the following JSON body:

    // {
    //   "UPSSecurity": {
    //     "UsernameToken": {
    //       "Username": "Your Username",
    //       "Password": "Your Password"
    //     },
    //     "ServiceAccessToken": {
    //       "AccessLicenseNumber": "Your Access License Number"
    //     }
    //   },
    //   "TrackRequest": {
    //     "Request": {
    //       "RequestOption": "1",
    //       "TransactionReference": {
    //         "CustomerContext": "Your Test Case Summary Description"
    //       }
    //     },
    //     "InquiryNumber": "YourTrackingNumber"
    //   }
    // }
    // 

    // Build the above JSON.
    let json = CkoJsonObject()!
    json.updateString(jsonPath: "UPSSecurity.UsernameToken.Username", value: "UPS_USERNAME")
    json.updateString(jsonPath: "UPSSecurity.UsernameToken.Password", value: "UPS_PASSWORD")
    json.updateString(jsonPath: "UPSSecurity.ServiceAccessToken.AccessLicenseNumber", value: "UPS_ACCESS_KEY")
    // Request all activity...
    json.updateString(jsonPath: "TrackRequest.Request.RequestOption", value: "activity")
    json.updateString(jsonPath: "TrackRequest.Request.TransactionReference.CustomerContext", value: "Your Test Case Summary Description")
    json.updateString(jsonPath: "TrackRequest.InquiryNumber", value: "1Z12345E0205271688")

    let sb = CkoStringBuilder()!
    let resp = CkoHttpResponse()!
    success = http.httpJson(verb: "POST", url: url, json: json, contentType: "application/json", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    print("status = \(resp.statusCode.intValue)")

    // A 200 response status indicate success.
    if resp.statusCode.intValue != 200 {
        print("\(resp.bodyStr!)")
        print("Failed.")
        return
    }

    json.load(json: resp.bodyStr)
    json.emitCompact = false
    print("\(json.emit()!)")

    // {
    //   "TrackResponse": {
    //     "Response": {
    //       "ResponseStatus": {
    //         "Code": "1",
    //         "Description": "Success"
    //       },
    //       "TransactionReference": {
    //         "CustomerContext": "Your Test Case Summary Description"
    //       }
    //     },
    //     "Shipment": {
    //       "InquiryNumber": {
    //         "Code": "01",
    //         "Description": "ShipmentIdentificationNumber",
    //         "Value": "1Z12345E0205271688"
    //       },
    //       "ShipmentType": {
    //         "Code": "01",
    //         "Description": "Small Package"
    //       },
    //       "ShipperNumber": "12345E",
    //       "Service": {
    //         "Code": "002",
    //         "Description": "2ND DAY AIR"
    //       },
    //       "ReferenceNumber": {
    //         "Code": "01",
    //         "Value": "LINE4AND115"
    //       },
    //       "PickupDate": "19990608",
    //       "Package": {
    //         "TrackingNumber": "1Z12345E0205271688",
    //         "Activity": [
    //           {
    //             "ActivityLocation": {
    //               "Address": {
    //                 "City": "ANYTOWN",
    //                 "StateProvinceCode": "GA",
    // 
    //                 "PostalCode": "30340",
    //                 "CountryCode": "US"
    //               },
    //               "Code": "ML",
    //               "Description": "BACK DOOR",
    //               "SignedForByName": "JOHN DOE"
    //             },
    //             "Status": {
    //               "Type": "D",
    //               "Description": "DELIVERED",
    //               "Code": "KM"
    //             },
    //             "Date": "19990610",
    //             "Time": "120000",
    //             "Document": {
    //               "Type": {
    //                 "Code": "01",
    //                 "Description": "Signature Image"
    //               },
    //               "Content": "R0lGODdhoA ... JU9Y8RdHsRKLMVJ4MVDMREAAADs=",
    //               "Format": {
    //                 "Code": "01",
    //                 "Description": "GIF"
    //               }
    //             }
    //           },
    //           {
    //             "Status": {
    //               "Type": "M",
    //               "Description": "BILLING INFORMATION RECEIVED. SHIPMENT DATE PENDING.",
    //               "Code": "MP"
    //             },
    //             "Date": "19990608",
    //             "Time": "120000"
    //           }
    //         ],
    //         "PackageWeight": {
    //           "UnitOfMeasurement": {
    //             "Code": "LBS"
    //           },
    //           "Weight": "5.00"
    //         },
    //         "ReferenceNumber": [
    //           {
    //             "Code": "01",
    //             "Value": "LINE4AND115"
    //           },
    //           {
    //             "Code": "08",
    //             "Value": "LJ67Y5"
    //           }
    //         ]
    //       }
    //     },
    //     "Disclaimer": "You are using UPS tracking service on customer integration test environment, please switch to UPS production environment once you finish the test. The URL is https://onlinetools.ups.com/webservices/Track"
    //   }
    // }

    // Use the online tool at Generate JSON Parsing Code
    // to generate JSON parsing code.

    var statusCode: String? = json.string(of: "TrackResponse.Response.ResponseStatus.Code")
    var statusDescription: String? = json.string(of: "TrackResponse.Response.ResponseStatus.Description")
    print("statusCode: \(statusCode!)")
    print("statusDescription\(statusDescription!)")
    var customerContext: String? = json.string(of: "TrackResponse.Response.TransactionReference.CustomerContext")
    var inquiryNumberCode: String? = json.string(of: "TrackResponse.Shipment.InquiryNumber.Code")
    var inquiryNumberDescription: String? = json.string(of: "TrackResponse.Shipment.InquiryNumber.Description")
    var inquiryNumberValue: String? = json.string(of: "TrackResponse.Shipment.InquiryNumber.Value")
    var shipmentTypeCode: String? = json.string(of: "TrackResponse.Shipment.ShipmentType.Code")
    var shipmentTypeDescription: String? = json.string(of: "TrackResponse.Shipment.ShipmentType.Description")
    var shipperNumber: String? = json.string(of: "TrackResponse.Shipment.ShipperNumber")
    var serviceCode: String? = json.string(of: "TrackResponse.Shipment.Service.Code")
    var serviceDescription: String? = json.string(of: "TrackResponse.Shipment.Service.Description")
    var referenceNumberCode: String? = json.string(of: "TrackResponse.Shipment.ReferenceNumber.Code")
    var referenceNumberValue: String? = json.string(of: "TrackResponse.Shipment.ReferenceNumber.Value")
    var pickupDate: String? = json.string(of: "TrackResponse.Shipment.PickupDate")
    var trackingNumber: String? = json.string(of: "TrackResponse.Shipment.Package.TrackingNumber")
    var unitOfMeasurementCode: String? = json.string(of: "TrackResponse.Shipment.Package.PackageWeight.UnitOfMeasurement.Code")
    var weight: String? = json.string(of: "TrackResponse.Shipment.Package.PackageWeight.Weight")
    var disclaimer: String? = json.string(of: "TrackResponse.Disclaimer")

    var i: Int = 0
    var activityCount: Int = json.size(ofArray: "TrackResponse.Shipment.Package.Activity").intValue
    print("activityCount: \(activityCount)")

    while i < activityCount {
        print("-- activity \(i)")
        json.i = i
        if json.hasMember(jsonPath: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.Address.City") == true {
            var city: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.Address.City")
            print("city: \(city!)")
            var provinceCode: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.Address.StateProvinceCode")
            var postalCode: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.Address.PostalCode")
            var countryCode: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.Address.CountryCode")
        }

        var locationCode: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.Code")
        var locationDescription: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.Description")
        var locationSignedForByName: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].ActivityLocation.SignedForByName")

        var activityStatusType: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Status.Type")
        print("activityStatusType: \(activityStatusType!)")
        var activityStatusDescription: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Status.Description")
        print("activityStatusDescription: \(activityStatusDescription!)")
        var activityStatusCode: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Status.Code")
        print("activityStatusCode: \(activityStatusCode!)")

        var activityDate: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Date")
        var activityTime: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Time")

        if json.hasMember(jsonPath: "TrackResponse.Shipment.Package.Activity[i].Document") == true {
            var typeCode: Int = json.int(of: "TrackResponse.Shipment.Package.Activity[i].Document.Type.Code").intValue
            var typeDescription: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Document.Type.Description")
            var documentContent: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Document.Content")
            var documentFormatCode: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Document.Format.Code")
            // Format description would be something like "GIF" for a signature image.
            var documentFormatDescription: String? = json.string(of: "TrackResponse.Shipment.Package.Activity[i].Document.Format.Description")

            // 01 - Signature Image
            // 02 - Delivery Receipt
            // 03 - Free Astray
            // 04 - POD
            if typeCode == 1 {
                // We have a signature image.  Get the image data and save to a file.
                let sbImagePath = CkoStringBuilder()!
                sbImagePath.append(value: "qa_output/sig_")
                sbImagePath.append(value: trackingNumber)
                sbImagePath.append(value: ".")
                sbImagePath.append(value: documentFormatDescription)
                let imageData = CkoBinData()!
                success = imageData.appendEncoded(encData: documentContent, encoding: "base64")
                // Write to "qa_output/sig_1Z12345E0205271688.GIF"
                success = imageData.writeFile(path: sbImagePath.getAsString())
            }

        }

        i = i + 1
    }

    i = 0
    var refnumCount: Int = json.size(ofArray: "TrackResponse.Shipment.Package.ReferenceNumber").intValue
    while i < refnumCount {
        json.i = i
        var refnumCode: String? = json.string(of: "TrackResponse.Shipment.Package.ReferenceNumber[i].Code")
        var refnumValue: String? = json.string(of: "TrackResponse.Shipment.Package.ReferenceNumber[i].Value")
        i = i + 1
    }

    print("Success.")

}