Search code examples
amazon-web-servicesamazon-s3aws-step-functions

About Uploading photo to AWS


I am developing a software on AWS DynamoDB. I got some UIImages. Where should upload them? S3?

I try to use S3, but it says it needs my photo to be a bundle resource. But what I got is an UIImage.

How can I convert UIImagge to NSBUNDLE?


Solution

  • You need to setup and execute an upload request:

    // Configure the authentication
    import AWSS3
    
    // configure S3
    let S3BucketName = "<#bucket#>"
    
    // configure authentication with Cognito
    let CognitoPoolID = "<#cognito-pool-id#>"
    let Region = AWSRegionType.<#region#>
    let credentialsProvider = AWSCognitoCredentialsProvider(regionType:Region,
        identityPoolId:CognitoPoolID)
    let configuration = AWSServiceConfiguration(region:Region, credentialsProvider:credentialsProvider)
    AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
    
    // Point to the image you want to upload
    let ext = "png"
    let imageURL = NSBundle.mainBundle().URLForResource("<#image-name#>", withExtension: ext)!
    
    // Setup the upload request
    let uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest.body = imageURL
    uploadRequest.key = NSProcessInfo.processInfo().globallyUniqueString + "." + ext
    uploadRequest.bucket = S3BucketName
    uploadRequest.contentType = "image/" + ext
    
    // Push the image
    let transferManager = AWSS3TransferManager.defaultS3TransferManager()
    transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
        if let error = task.error {
            print("Upload failed (\(error))")
        }
        if let exception = task.exception {
            print("Upload failed (\(exception))")
        }
        if task.result != nil {
            let s3URL = NSURL(string: "http://s3.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")!
            print("Uploaded to:\n\(s3URL)")
        }
        else {
            print("Unexpected empty result.")
        }
        return nil
    }
    

    You can now create a UIImage instance by doing: let image = UIImage(data: NSData(contentsOfURL: s3URL)!)