Upload video to Amazon S3 from Swift - ios

I want to upload a video on Amazon S3 using Swift but I can not find any online help.
Can someone help me?
Thank you!
https://docs.aws.amazon.com/en_us/aws-mobile/latest/developerguide/mobile-hub-add-aws-mobile-user-data-storage.html

1) Create a Podfile:
platform :ios, '8.0'
inhibit_all_warnings!
use_frameworks!
target 'AmazonS3Upload' do
pod 'AWSS3'
end
Run the next command from Terminal:
pod install
Open the generated workspace. And after that we can implement uploading of files using frameworks from Pods.
We need to import 2 modules:
import AWSS3
import AWSCore
Set up a AWS configuration using your credentials. For example:
let accessKey = "..."
let secretKey = "..."
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region: AWSRegionType.usEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
Create an upload request:
let url = ...URL to your file...
let remoteName = "Name of uploaded file"
let S3BucketName = "Name of your bucket on Amazon S3"
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = url
uploadRequest.key = remoteName
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/jpeg"
uploadRequest.acl = .publicRead
And upload using AWSS3TransferManager.
let transferManager = AWSS3TransferManager.default()
transferManager?.upload(uploadRequest).continue({ (task: AWSTask) -> Any? in
if let error = task.error {
print("Upload failed with error: ((error.localizedDescription))")
}
if let exception = task.exception {
print("Upload failed with exception ((exception))")
}
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
print("Uploaded to:\(publicURL)")
}
return nil
})

You can also follow https://aws-amplify.github.io/docs/ios/storage to use Amplify CLI to provision S3 and Amplify framework's Storage plugin to interact with S3.

Related

Amazon S3 bucket upload image with iOS app

Using cocoapod AWS file for uploading
pod 'AWSS3'
pod 'AWSCognito'
pod 'AWSCore'
creating configuration using accesskey and secretkey
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
Trying to upload an image with transferutility
transferUtility!.uploadData(imageData! as Data,
bucket: S3BucketName,
key: fileName,
contentType: "image/*",
expression: expression,
completionHandler: completionHandler).continueWith {
(task) -> AnyObject? in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let result = task.result {
print ("upload successful.")
print (result.response)
}
return nil;
}
Getting an error at completion handler with
Domain=com.amazonaws.AWSS3TransferUtilityErrorDomain Code=2 "(null)" UserInfo={Server=AmazonS3, Transfer-Encoding=Identity, Connection=close, Content-Type=application/xm}

Upload image to S3 with Amazon Educate Starter Account

I just want to upload an image to S3, but I am using AWS Educate Account and I'm trying since 4 hours to get this done and have ZERO ideas what isn't working correctly.
So I've set up everything on the AWS console and the bucket is public to EVERYONE + Region US West N.Virginia like it should be with AWS Educate Accounts.
So here is my code:
let accessKey = "accessKey"
let secretKey = "secretKey"
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let transferUtility = AWSS3TransferUtility.default()
let bucketname = "bucketname"
let expression = AWSS3TransferUtilityUploadExpression()
transferUtility.uploadData(jpegData, bucket: bucketname, key: "myTransferUtilityUpload.jpg", contentType: "image/jpg", expression: expression) { (task, error) in
if let error = error {
print(error.localizedDescription)
}
if let response = task.response {
print(response)
}
}
Can anyone tell me what I do wrong?
I get this error message:
The operation couldn’t be completed.
(com.amazonaws.AWSS3TransferUtilityErrorDomain error 2.)
accessKey + secretKey I got from Account Details + AWS CLI on the 'Welcome to AWS Educate Starter Account' Dashboard and obviously the bucket name is the same name like in my console
EDIT:
if let jpegData = image.jpegData(compressionQuality: 0.7) {
let fileManager = FileManager.default
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
var sourceFolderURL = documentDirectory.appendingPathComponent("image.jpg")
do {
try jpegData.write(to: sourceFolderURL)
} catch {
print(error.localizedDescription)
completionHandler(nil)
return
}
let accessKey = "-"
let secretKey = "-"
let bucketname = "-"
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = sourceFolderURL
uploadRequest.key = "image.jpg"
uploadRequest.bucket = bucketname
uploadRequest.contentType = "image/jpeg"
uploadRequest.acl = .publicReadWrite
let transferManager = AWSS3TransferManager.default()
transferManager.upload(uploadRequest).continueWith { [weak self] (task) -> Any? in
if let error = task.error {
print("Upload failed with error: (\(error.localizedDescription))")
completionHandler(nil)
return nil
}
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
if let absoluteString = publicURL?.absoluteString {
print("Uploaded to:\(absoluteString)")
completionHandler(nil)
}
}
completionHandler(nil)
return nil
}
}
}
I have uploaded an image to S3 bucket with the following code:
First, save the image to a temporary directory.
func uploadImageToS3(imageName:String, completion:#escaping (Bool) -> Void) {
let accessKey = "accessKey"
let secretKey = "secretKey"
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region:AWSRegionType.APSoutheast2, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let S3BucketName = "bucketname"
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = self.getImageURLWithName(imageName:imageName)
uploadRequest.key = "\(imageName)"
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/jpeg"
//You can specify private or public here
uploadRequest.acl = .private
let transferManager = AWSS3TransferManager.default()
transferManager.upload(uploadRequest).continueWith { [weak self] (task) -> Any? in
ProgressIndicatorHelper.hideGlobalHUD()
if let error = task.error {
print("Upload failed with error: (\(error.localizedDescription))")
completion(false)
}
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
if let absoluteString = publicURL?.absoluteString {
print("Uploaded to:\(absoluteString)")
completion(true)
}
}
return nil
}
}
For getting image from Path following code I have used:
func getImageURLWithName(imageName:String) -> URL {
var sourceImageURL: URL!
let fileManager = FileManager.default
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
var sourceFolderURL:URL!
sourceFolderURL = documentDirectory.appendingPathComponent("YourTempFolder")
sourceImageURL = sourceFolderURL.appendingPathComponent(imageName)
}
return sourceImageURL
}
Hope this helps.
Moreover: Right now I don't think you can directly upload image from memory.
I searched for it. Following are links for same:
https://github.com/aws-amplify/aws-sdk-ios/issues/42
How to upload a UIImage to S3 with AWS iOS SDK v2
Let me know if you find any error.
Maybe it's a policy issue?
Try attaching this policy to your bucket (bucket policies)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": [
"arn:aws:s3:::mybucketname/*"
]
}
]
}

How to use AWS Rekognition to Compare Face in Swift 3

I've been trying to use the AWSRekognition SDK in order to compare face. However, Amazon has no Documentation on how to integrate their SDK with iOS. They have links that show how to work with Recognition (Developer Guide) with examples only in Java and very limited.
I wanted to know if anyone knows how to integrate AWS Rekognition in Swift 3. How to Initialize it and make a request with an image, receiving a response with the labels.
I have AWS Signatures AccessKey, SecretKey, AWS Region, Service Name. also Body
{
"SourceImage": {
"S3Object": {
"Bucket": "bucketName",
"Name": "ios/sample.jpg"
}
},
"TargetImage": {
"S3Object": {
"Bucket": "buketName",
"Name": "ios/target.JPG"
}
}
}
how can I initialize Rekognition and build a Request.
Thanks you!
Instantiate the Rekognition Client, Here I'm using the client with the default configuration.
let rekognitionClient:AWSRekognition = AWSRekognition.default()
Otherwise, you can use the credentials as follows:
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType: AWSRegionType.usEast2,
identityPoolId: "us-east-2_myPoolID")
let configuration = AWSServiceConfiguration(
region: AWSRegionType.usEast2,
credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let rekognitionClient:AWSRekognition = AWSRekognition.default()
Now construct the request and set the image in it.
let image = UIImage(named: "MyImage")
let request = AWSRekognitionDetectLabelsRequest()
request.image = image
request.maxLabels = <num_labels_needed>
request.minConfidence = <confidence_interval_needed>
Now to compare faces, read about the CompareFacesRequest: https://github.com/aws/aws-sdk-ios/blob/master/AWSRekognition/AWSRekognitionService.m#L288
There is a sample test in the SDK that compares two faces in ObjC but you can translate that in Swift:
https://github.com/aws/aws-sdk-ios/blob/master/AWSRekognitionUnitTests/AWSGeneralRekognitionTests.m#L60
let key = "testCompareFaces"
let configuration = AWSServiceConfiguration(region: AWSRegionUSEast2, credentialsProvider: nil)
AWSRekognition.register(with: configuration, forKey: key)
AWSRekognition(for: key).compareFaces(AWSRekognitionCompareFacesRequest()).continue(withBlock: {(_ task: AWSTask) -> Any in
print("completed")
Swift 5.0
let key = "testCompareFaces"
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: "Add_access_key_id", secretKey:"Add_secret_access_key_id")
let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
AWSRekognition.register(with: configuration!, forKey: key)
let rekognition = AWSRekognition(forKey: key)
guard let request = AWSRekognitionCompareFacesRequest() else {
puts("Unable to initialize AWSRekognitionDetectLabelsRequest.")
return
}
let sourceImage = AWSRekognitionImage()
sourceImage!.bytes = sourceImage.jpegData(compressionQuality: 0.4)// Specify your source image
request.sourceImage = sourceImage
let targetImage = AWSRekognitionImage()
targetImage!.bytes = targetImage.jpegData(compressionQuality: 0.4) // Specify your target image
request.targetImage = targetImage
rekognition.compareFaces(request) { (respone, error) in
if error == nil {
if let response = respone {
if let first = response.faceMatches?.first {
print(first)
}
}
} else {
print(error?.localizedDescription)
}
}

awss3transfermanager background uploads success but not in bucket

I am using AWSS3TransferManager to upload files directly to s3. I am getting a success message back from the upload block but it isn't appearing in my bucket in the s3 management console. When I visit the url directly it appears though. I need this to be added to the bucket because my app pulls from an sqs queue in order to create the object in the db.
Here is my code for uploading:
let uploadFileRequest = AWSS3TransferManagerUploadRequest()
uploadFileRequest.bucket = AWS.S3BucketName
uploadFileRequest.key = uploadFileName
uploadFileRequest.contentType = "video/quicktime"
uploadFileRequest.contentLength = NSNumber(integer: video!.length)
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
uploadFileRequest.body = uploadFileURL!
transferManager.upload(uploadFileRequest).continueWithBlock({ (task) -> AnyObject! in
if task.error != nil {
print("video upload failed \(task.error)")
} else {
print("video upload succeeded")
print("\(uploadFileName)")
}
return 1
})
update:
I think this may be a security issue. Here is my code for setting up cognito:
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:
AWSRegionType.USEast1, identityPoolId: AWS.cognitoPoolID)
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

Display UIImageView using Swift from AWS

I'm trying to render an image in UIImageView using Swift. The source object is located in an AWS S3 bucket. I could not find any example code on Google. So I tried to translate the code given in this link [AWS S3 SDK v2 for iOS - Download an image file to UIImage from Obj-C to Swift, but failed. I'm a beginner in iOS.
let accessKey = "ACCESS_CODE";
let secretKey = "SECRET_KEY";
// let credentialsProvider = AWSStaticCredentialsProvider.credentialsWithAccessKey(accessKey, secretKey: secretKey)
// ^ Xcode says - credentialsWithAccessKey is deprecated, use initWithAccessKey
let credentialsProvider = AWSStaticCredentialsProvider.initWithAccessKey(accessKey, secretKey: secretKey)
// ^ Xcode says - AWSStaticCredentialsProvider.Type does not have a member named ‘initWithAccessKey’
I could be doing very many things wrong here, even silly mistakes. The best help would be to point to some example code.
Have you tried like this
var credentialsProvider: AWSStaticCredentialsProvider = AWSStaticCredentialsProvider.credentialsWithAccessKey("MY_ACCESS_KEY", secretKey: "MY_SECRET_KEY")
var configuration: AWSServiceConfiguration = AWSServiceConfiguration.configurationWithRegion(AWSRegionUSWest1, credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
var transferManager: AWSS3 = AWSS3(configuration: configuration)
var getImageRequest: AWSS3GetObjectRequest = AWSS3GetObjectRequest.new()
getImageRequest.bucket = "MY_BUCKET"
getImageRequest.key = "MY_KEY"
transferManager.getObject(getImageRequest).continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock: {(task: BFTask) -> id in if task.error {
NSLog("Error: %#", task.error)
}
else {
NSLog("Got image")
var data: NSData = task.result.body()
dispatch_async(dispatch_get_main_queue(), {
var image: UIImage = UIImage.imageWithData(data)
myImageView.image = image
})
I created a custom class to download image. It worked for me.
class AWSImageDownloader {
init(AccessKey accessKey:String, SecretKey secretKey:String, andRegion region:AWSRegionType = .USEast1) {
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
guard let configuration = AWSServiceConfiguration(region: region, credentialsProvider: credentialsProvider) else {
debugPrint("Failed to configure")
return
}
AWSServiceManager.default().defaultServiceConfiguration = configuration
}
func downloadImage(Name imageName:String, fromBucket bucketName:String, onDownload successCallback:#escaping AWSImageDownloadSuccess, andOnError errorCallback:#escaping AWSImageDownloadError){
let transferManager = AWSS3.default()
let getImageRequest = AWSS3GetObjectRequest()
getImageRequest?.bucket = bucketName
getImageRequest?.key = imageName
transferManager.getObject(getImageRequest!).continueWith(executor: AWSExecutor.mainThread()) { (anandt) -> Void in
if anandt.error == nil {
if let imageData = anandt.result?.body as? Data, let image = UIImage(data: imageData) {
successCallback(image)
} else {
errorCallback("Download failed")
}
} else {
let error = "Error \(anandt.error?.localizedDescription ?? "unknown by dev")"
errorCallback(error)
}
}
}
}

Resources