I'm uploading data from my Swift app to Amazon S3 and it drains battery like nothing else. How can this be avoided?

Viewed 486

In my 'Swift' app I have a feature of uploading photos to my Amazon S3 bucket. When the user is connected to WiFi or LTE, there's no problem, but when the connection is a little slower (e.g. 3G), then the upload takes a lot of time (up to one minute) and iphone can lose 15-20% of battery! I resize photos down to around 200-300kb, so that should not be a problem. The code that I use for that is:

func awsS3PhotoUploader(_ ext: String, pathToFile: String, contentType: String, automaticUpload: Bool){

        let credentialsProvider = AWSCognitoCredentialsProvider(regionType:CognitoRegionType,
                                                                identityPoolId:CognitoIdentityPoolId)
        let configuration = AWSServiceConfiguration(region:CognitoRegionType, credentialsProvider:credentialsProvider)
        AWSServiceManager.default().defaultServiceConfiguration = configuration

        let uploadRequest = AWSS3TransferManagerUploadRequest()
        uploadRequest?.body = URL(string: "file://"+pathToFile)
        uploadRequest?.key = ProcessInfo.processInfo.globallyUniqueString + "." + ext
        uploadRequest?.bucket = S3BucketName
        uploadRequest?.contentType = contentType + ext

        uploadRequest?.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in
            DispatchQueue.main.async(execute: { () -> Void in
                if totalBytesExpectedToSend > 1 {
                    print(totalBytesSent)
                    print(totalBytesExpectedToSend)
                }
            })
        }
        let transferManager = AWSS3TransferManager.default()
        transferManager?.upload(uploadRequest).continue({ (task) -> AnyObject! in

            if (task.isCompleted) {
                  print("task completed")
            }

            if let error = task.error {
                 print("Upload failed ❌ (\(error))")

            }
            if let exception = task.exception {
                 print("Upload failed ❌ (\(exception))")

            }
            if task.result != nil {
                let s3URL: String = "https://myAlias.cloudfront.net/\((uploadRequest?.key!)!)"
                print("Uploaded to:\n\(s3URL)")
            }
            else {
                print("Unexpected empty result.")
            }
            return nil
        }
        )

}

Is there anything that comes up to your mind of what am I doing wrong here and how could this huge battery consumption be avoided?

1 Answers
Related