Swift AWS S3: Delete File from an S3 Bucket

Back to Index

Demonstrates how to delete a file from an S3 bucket. This example deletes the file /chilkat.ocean/starfishCopy.jpg. A response status code equal to 204 is returned for success (with an empty response body).

Documentation: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html

CURL Command

curl -X DELETE https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg

Swift Example


func chilkatTest() {
    let rest = CkoRest()
    var success: Bool

    let authAws = CkoAuthAws()
    authAws.AccessKey = "AWS_ACCESS_KEY"
    authAws.SecretKey = "AWS_SECRET_KEY"
    authAws.Region = "us-west-2"
    authAws.ServiceName = "s3"
    rest.SetAuthAws(authAws)

    //  URL: https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg
    var bTls: Bool = true
    var port: Int = 443
    var bAutoReconnect: Bool = true
    success = rest.Connect("chilkat.ocean.s3.us-west-2.amazonaws.com", port: port, tls: bTls, autoReconnect: bAutoReconnect)
    if success != true {
        print("ConnectFailReason: \(rest.ConnectFailReason.intValue)")
        print("\(rest.LastErrorText)")
        return
    }

    let sbResponseBody = CkoStringBuilder()
    success = rest.FullRequestNoBodySb("DELETE", uriPath: "/starfishCopy.jpg", sb: sbResponseBody)
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    var respStatusCode: Int = rest.ResponseStatusCode.intValue
    if respStatusCode >= 400 {
        print("Response Status Code = \(respStatusCode)")
        print("Response Header:")
        print("\(rest.ResponseHeader)")
        print("Response Body:")
        print("\(sbResponseBody.GetAsString())")
        return
    }


}