Checking metadata of Amazon S3 file using iOS AWS

2020-04-16 19:47发布

问题:

I am using the AWS iOS SDK v2, and Swift 1.2.

I am storing my app's app.json file on S3 and want to check it at launch to see if it's been updated since the last run. According to research, simply doing a HEAD request on the object should return the "Last-Modified" attribute which can then be compared to the previous.

The problem is that doing a HEAD request on an Object doesn't really seem to be well documented. I've got the following:

var metaDataRequest = AWSS3HeadObjectRequest()
metaDataRequest.bucket = S3BucketName
metaDataRequest.key = S3AppJSONKey

This seems like a decent start, however I cannot find a way to execute the request. The AWSS3TransferManager has a download() method, but the method requires an AWSS3TransferManagerDownloadRequest type, which an AWSS3HeadObjectRequest cannot be cast as.

Not sure where to go from here, short of just doing the request outside of the SDK. I did, however, want to leverage as much of the SDK as possible, so if this is possible I would love to know how.

回答1:

You need to use AWSS3 (instead of AWSS3TransferManager) to call - headObject:.



回答2:

You need to call headobject method of AWSS3

     var request = AWSS3HeadObjectRequest()

    request.bucket = "flkasdhflhad"
    request.key = "hfsdahfjkhadjkshf"

   request.ifModifiedSince = NSDate()


  var s3 = AWSS3.defaultS3()

    s3.headObject(request) { ( output1 : AWSS3HeadObjectOutput?, error : NSError?) -> Void in
   print( output1?.description())
    }

if your object is modified from specified date then it will return u the object otherwise it will return u the status code 304.



回答3:

You can use following Swift 2.2 method to check if file exist or not

func checkIfFileExist() {
    let s3 = AWSS3.defaultS3()
    let headObjectsRequest = AWSS3HeadObjectRequest()
    headObjectsRequest.bucket = "YourBucketName" //Don't add "/" at end of your bucket Name    

    headObjectsRequest.key = "YourFileNameYouWantToCheckFor" //Don't add "/" in start of file name 

    s3.headObject(headObjectsRequest).continueWithBlock { (task) -> AnyObject! in
        if let error = task.error {
            print("Error to find file: \(error)")

        } else {
            print("fileExist")
        }
    }

}

Note: Example to set bucket and key

suppose you have bucket named "ABC" and than folder named "XYZ" and than inside "XYZ" you have file "abc123"

than write

headObjectsRequest.bucket = "ABC/XYZ"

and

headObjectsRequest.key = "abc123"

and if you want to check for the entire folder

than use

headObjectsRequest.bucket = "ABC/XYZ"

and

headObjectsRequest.key = ""

Thanks Mohsin