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}
Related
We are trying to upload audio to AWS S3 bucket using method(AWSS3TransferUtility). Pod - AWSS3. We are getting below error.
Error description:
Error Domain=com.amazonaws.AWSS3TransferUtilityErrorDomain Code=2 "(null)" UserInfo={Server=AmazonS3, Transfer-Encoding=Identity, Connection=close, Content-Type=application/xml, Date=Fri, 06 Sep 2021 04:43:50 GMT, x-amz-request-id=VH53PCCWA529FDRC, x-amz-id-2=4uZoqJj+TJ93WUBSnrC889CAj3gkGGw/V6iJjhrVjB2+ZygTflGcPAV+amfxmeBGeGHHVXv3nHk=}
func uploadFile(withImage image: UIImage) {
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:AWSRegionType.USEast2,
identityPoolId:"us-east-2:fe41c293-df49-49a4-886d-094f2cd8d0fd")
let configuration = AWSServiceConfiguration(region:.USEast2, credentialsProvider:credentialsProvider)
let tuConf = AWSS3TransferUtilityConfiguration()
AWSS3TransferUtility.register(
with: configuration!,
transferUtilityConfiguration: tuConf,
forKey: "transfer-utility-with-advanced-options"
)
let transferUtility = AWSS3TransferUtility.s3TransferUtility(forKey: "transfer-utility-with-advanced-options")
AWSServiceManager.default().defaultServiceConfiguration = configuration
let s3BucketName = "testingimageupload"
let data: Data = image.pngData()!
let remoteName = generateRandomStringWithLength(length: 12)+"."+"png"
print("REMOTE NAME : ",remoteName)
let expression = AWSS3TransferUtilityUploadExpression()
expression.setValue("public-read", forRequestHeader: "x-amz-acl")
expression.progressBlock = { (task, progress) in
DispatchQueue.main.async(execute: {
// Update a progress bar
})
}
var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async(execute: {
})
}
transferUtility!.uploadData(data, bucket: s3BucketName, key: "private/Abhay/" + remoteName, contentType: "image/"+"png", expression: expression, completionHandler: completionHandler).continueWith { (task) -> Any? in
if let error = task.error {
print("Error : \(error.localizedDescription)")
}
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(s3BucketName).appendingPathComponent(remoteName)
if let absoluteString = publicURL?.absoluteString {
// Set image with URL
print("Image URL : ",absoluteString)
}
}
return nil
}
Prerequisite : Setup AWS Amplify CLI.
1. Project initialisation.
amplify init: Setup AWS Amplify locally & remote.
Note: amplify init command not found
1)`npm install -g #aws-amplify/cli` - ### install the Amplify CLI ###
2)`curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL` ### configured $Path correctly ###
3)`amplify init` ###Try Amplify init###
Amplify Demo project or click enter for the default name : Enter a name for the project
Dev or click enter for the default name : Enter a name for the Environment
Choose Visual Studio Code : Choose your default Editor
iOS : Choose the type of app that you’re building
yes : Do you want to use an AWS Profile?
2. Project Storage setup
amplify add storage : Add storage
Content(Images, audio, video, etc.) : Select the below mentioned services
yes : (Amazon Cognito) Do you want to add auth now?
No: Do you want to configure advanced settings?
bucket name or click enter for the default name : Please provide bucket name
Auth users only or Auth and guest users : Who should have access
create/update , read , delete. : What kind of access do you want for Authenticated users?
create/update , read , delete.: What kind of access do you want for guest users?
No : Do you want add a lama trigger for your S3 Bucket?
3. Push - Amplify configuration to backend
amplify push : Amplify Push
Yes: are you sure you want to continue ?
Pod install
target ‘ProjectName do
use_frameworks!
pod 'Amplify'
pod 'AmplifyPlugins/AWSS3StoragePlugin'
pod 'AmplifyPlugins/AWSCognitoAuthPlugin'
end
Code: ViewController.swift
import Amplify
import AmplifyPlugins
func configureAmplify() {
do {
try Amplify.add(plugin: AWSCognitoAuthPlugin())
try Amplify.add(plugin: AWSS3StoragePlugin())
try Amplify.configure()
print("Successfully configured Amplify")
} catch {
print("Could not configure Amplify", error)
}
}
func uploadFile() {
let audioUrl = URL(string: "/Users/appaiah/Downloads/RealAudio.mp3")!
Amplify.Storage.uploadFile(key: fileKey, local: audioUrl){ // let fileKey = "SampleAudio.mp3"
result in
switch result {
case .success(let key):
print("file with key uploaded \(key)")
case .failure(let error):
print("failed \(error)")
}
}
}
func downloadFile(){
let downloadToFileName = getTermsOfUseURL()
Amplify.Storage.downloadFile(
key: fileKey,
local: downloadToFileName,
progressListener: { progress in
print("Progress: \(progress)")
}, resultListener: { event in
switch event {
case .success:
print("Completed")
DispatchQueue.main.async { }
case .failure(let storageError):
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
})
}
func getTermsOfUseURL() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
print(paths[0].appendingPathComponent(fileKey))
return paths[0].appendingPathComponent(fileKey)
}
I am trying to download an object from existing s3 bucket to IOS app using amplify-swift.
I've followed the tutorial to init amplify, and import storage.
I am trying to do a call for an unauthenticated user->
In Cognito console I defined a role for unauth user, (and allowed access to unauth users), gave him permissions to my bucket and verified with simulator that getObject works.
When calling this code:
let key = "images/some_file.txt"
do {
try Amplify.add(plugin: AWSCognitoAuthPlugin())
try Amplify.add(plugin: AWSS3StoragePlugin())
try Amplify.configure()
print("Amplify configured with storage plugin")
} catch {
print("Failed to initialize Amplify with \(error)")
}
Amplify.Storage.downloadData(
key: key,
progressListener: { progress in
print("Progress: \(progress)")
}, resultListener: { (event) in
switch event {
case let .success(data):
print("Completed: \(data)")
case let .failure(storageError):
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
})
I get this error:
Amplify configured with storage plugin 2021-03-31 18:09:09.988304+0300
ota[30840:728969] [] nw_protocol_get_quic_image_block_invoke dlopen
libquic failed Progress: <NSProgress: 0x6000001d50e0> : Parent: 0x0
(portion: 0) / Fraction completed: 0.0000 / Completed: 243 of -1
Failed: The HTTP response status code is [403].. TODO some status code
to recovery message mapper. For more information on HTTP status codes,
take a look at https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
I checked that the pool id, bucket name are all defined correctly in the json files.
What am I missing?
EDIT:
this seems to work, so i know the actual problem is not with the permissions, but rather with the amplify default download:
let expression = AWSS3TransferUtilityDownloadExpression()
expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: {
print("Downloading...")
})
}
let credentialProvider = AWSCognitoCredentialsProvider(regionType: .EUWest1, identityPoolId: "eu-west-1:xxxxxx")
let configuration = AWSServiceConfiguration(region: .EUWest1, credentialsProvider: credentialProvider)
AWSS3TransferUtility.register(with: configuration!, forKey: "customTU")
let tu = AWSS3TransferUtility.s3TransferUtility(forKey: "customTU")
tu?.downloadData(fromBucket: bucket, key: _key, expression: expression) { (task, URL, data, error) in
if error != nil {
print(error!)
}
DispatchQueue.main.async(execute: {
print("Got here")
let rawJSON = (String(data: data!, encoding: .utf8))!
print(rawJSON)
})
}
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.
Im trying to upload image to Aws S3 bucket. I tried to follow a tutorial and I'm getting a error saying "Returning ENOTCONN because protocol has not yet been set up." I'm new to swift and I'm not able to understand why the error is occurring also.My code for S3 upload is as follows:
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest?.body = url!
uploadRequest?.key = remoteFileName
uploadRequest?.bucket = S3BucketName
uploadRequest?.contentType = "image/" + ext
let transferManager = AWSS3TransferManager.default()
// Perform Upload
transferManager.upload(uploadRequest!).continueWith(block: { (task:AWSTask<AnyObject>) -> AnyObject! in
if let error = task.error{
print("error \(error.localizedDescription)")
}
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
})
My S3 is in ap-south-1 and cognito pool id in us-west-2. I guess thats creating the problem.Is there a way to fix the issue without creating another bucket in us-west-2.
I get the following error:
You want the bucket policy to be somewhat like this if the cognito pool is not set up for authentication: Notice Principal and Action values
Also, is there any particular reason you're using AWSS3TransferManagerUploadRequest? If the policy doesn't resolve your issue, you can use the following code for AWSS3TransferUtilityUploadExpression which sends your data in chunks asynchronously.
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = progressBlock
transferUtility.uploadData(UIImagePNGRepresentation(imageNew!)!,
bucket: "bucket-name",
key: (imgName.removeWhitespace()),
contentType: "image/png",
expression: expression,
completionHandler: completionHandler).continueWith { (task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
print("Upload Starting!")
// Do something with uploadTask.
}
return nil;
}
In my application, I am trying to upload image using AWS S3. But, When i am selecting image from library or captured image,in uploading process my application is getting crashed.
let path:NSString = (NSTemporaryDirectory() as NSString).appendingPathComponent("testImage.png") as NSString
let imageData:NSData = UIImagePNGRepresentation(image)! as NSData
imageData.write(toFile: path as String, atomically: true)
let url:NSURL = NSURL(fileURLWithPath: path as String)
let expression = AWSS3TransferUtilityUploadExpression()
expression.setValue("public-read", forRequestParameter: "x-amz-acl")
expression.setValue("public-read", forRequestHeader: "x-amz-acl" )
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadFile(url as URL!, bucket: bucketURL, key: myImageUploadKey , contentType: "image/png", expression: expression, completionHandler: { (task, error) in
if error != nil{
print(error?.localizedDescription ?? "error")
}else{
print(task.response ?? "Response error")
}
})
expression.progressBlock = { (task: AWSS3TransferUtilityTask, progress: Progress) in
print("progress \(progress.fractionCompleted)")
}
application is getting crashed at let transferUtility = AWSS3TransferUtility.default()
So please suggest any solution. It will be highly appreciated.Thanks.
May be this issue is coming due to AWS S3 pod updation. Please check the latest pods. Please check out this https://github.com/aws/aws-sdk-ios