AWSFirehoseRecorder saveRecord seems never saving any record - ios

In app didFinishLaunchingWithOptions
let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "my-identity-pool-id")
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialProvider)
AWSFirehoseRecorder.register(with: configuration!, forKey: "somestupidkey")
In view controller
let firehoseRecorder = AWSFirehoseRecorder(forKey: "somestupidkey")
let yourData = "Test_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_dataTest_data".data(using: .utf8)
firehoseRecorder.saveRecord(yourData, streamName: kinesisDirectory)
NSLog("Added %d records", firehoseRecorder.diskBytesUsed) // ALWAYS ZERO!!!!
It looks like it's not writing data at all. diskBytesUsed always returns 0. Any idea what might be issue?
Thanks

Ok, solved it. It turned to be authentication issue. So using this code will actually catch the error message of why the records weren't submitted:
firehoseRecorder?.saveRecord(jsonData, streamName: "YourStreamName").continueOnSuccessWith(block: { (task:AWSTask) -> AWSTask? in
NSLog("RecordBeen saved")
return nil;
}).continueWith(block: { (task:AWSTask) -> Any? in
if let error = task.error as? NSError {
print("Error: \(error)")
return nil
}
return nil
})
Showing error messages actually helped.
Hope it helps someone else having same issue.
Thanks.

Related

Loading images from external storage using Core Graphics not working iOS 13

I am attempting to load photos located on external storage (SD card) using core graphics in iOS 13 (beta). The code below works fine when the files are on the device. When the files are on external storage however it fails returning nil and I don't know why.
I believe I am using the correct security scoping.
I loaded the file URLs from a security scoped folder url as per Providing Access to Directories
guard folderUrl.startAccessingSecurityScopedResource() else {
return nil
}
defer { folderUrl.stopAccessingSecurityScopedResource() }
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, options) else {
throw Error.failedToOpenImage(message: "Failed to open image at \(imageURL)")
}
So... for my own project, where I ran into the same issue, I now have the following function to give me a thumbnail, going from elegant and quick to brute force.
static func thumbnailForImage(at url: URL, completion: (Result<UIImage, Error>) -> Void) {
let shouldStopAccessing = url.startAccessingSecurityScopedResource()
defer { if shouldStopAccessing { url.stopAccessingSecurityScopedResource() } }
let coordinator = NSFileCoordinator()
var error: NSError?
coordinator.coordinate(readingItemAt: url, options: .withoutChanges, error: &error) { url in
var thumbnailImage: UIImage?
var storedError: NSError?
var imageSource: CGImageSource?
print("Strategy 1: Via URL resource key")
do {
let resourceKeys = Set([URLResourceKey.thumbnailDictionaryKey])
let resources = try url.resourceValues(forKeys: resourceKeys)
if let dict = resources.thumbnailDictionary, let resource = dict[URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey] {
thumbnailImage = resource
} else {
throw "No thumbnail dictionary"
}
} catch let error {
storedError = error as NSError
}
let options = [kCGImageSourceCreateThumbnailFromImageIfAbsent: true, kCGImageSourceShouldAllowFloat: true, kCGImageSourceCreateThumbnailWithTransform: true]
if thumbnailImage == nil {
print("Strategy 2: Via CGImageSourceCreateWithURL")
imageSource = CGImageSourceCreateWithURL(url as CFURL, options as CFDictionary)
}
if thumbnailImage == nil && imageSource == nil {
print("Strategy 3: Via CGImageSourceCreateWithData")
let data = try? Data.init(contentsOf: url)
if let data = data {
imageSource = CGImageSourceCreateWithData(data as CFData, options as CFDictionary)
}
}
if let imageSource = imageSource, thumbnailImage == nil {
print("Attempting thumbnail creation from source created in strategy 2 or 3")
if let image = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) {
thumbnailImage = UIImage(cgImage: image)
}
}
if let thumbnailImage = thumbnailImage {
print("Success")
completion(.success(thumbnailImage))
} else {
print("Failure")
if let error = storedError { completion(.failure(error)) }
else { completion(.failure("Everything just fails...")) }
}
}
if let error = error { completion(.failure(error)) }
}
Basically it works by trying to get a thumbnail via the URL resources first. This is the quickest and nicest way, of it works. If that fails, I try CGImageSourceCreateWithURL. That works most of the time, except on remote storage. I suspect that's still a bug and submitted a feedback ticket to apple for this. I suggest you do the same. Last attempt, just try to read the entire file using NSData and creating an image source via CGImageSourceCreateWithData...
So far, if it's an image file I, this seems to produce a thumbnail most of the time. It can be quite slow though, having to read the entire file.

AWS Lambda swift SDK authentication with user pools

I am using user pools with my iOS mobile app.
I would like to access my lambda functions using the sdk but can't find documentation on how to provide the authentication necessary. Also unclear as to whether I need to use the API Gateway if I am using the sdk with user pools.
I am using this method to access my lambda function:
private func invokeLambda(data: [String: Any]) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let pool = appDelegate.pool
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "MyIdentityPoolId", identityProviderManager:pool)
let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let lambdaInvoker = AWSLambdaInvoker.default()
let jsonObject: [String: Any] = data
lambdaInvoker.invokeFunction("myFunction", jsonObject: jsonObject).continueWith(block: {(task:AWSTask<AnyObject>) -> Any? in
if let error = task.error as NSError? {
if (error.domain == AWSLambdaInvokerErrorDomain) && (AWSLambdaInvokerErrorType.functionError == AWSLambdaInvokerErrorType(rawValue: error.code)) {
print("Function error: \(error.userInfo[AWSLambdaInvokerFunctionErrorKey])")
} else {
print("Error: \(error)")
}
return nil
}
// Handle response in task.result
if let JSONDictionary = task.result as? NSDictionary {
print("Result: \(JSONDictionary)")
print("resultKey: \(JSONDictionary["resultKey"])")
}
return nil
})
}
I am getting the following error:
"AccessDeniedException"
Edit #1
The error that I am getting indicates the unauth role is being used for access rather than the auth role. the user is correctly logged in and the token is valid. Not sure where I am going wrong here.
Try attaching AWSLambdaInvocation-DynamoDB to the role.

AWS: DeveloperAuthenticatedIdentityProvider not firing IOS Swift

I am trying to integrate S3 upload to upload a video file and tried Developer authenticated Identity method. Everything is configured as per the aws docs says.
DeveloperAuthenticatedIdentityProvider Class :
class DeveloperAuthenticatedIdentityProvider : AWSCognitoCredentialsProviderHelper {
override func token() -> AWSTask<NSString> {
//return AWSTask //with token and will set identityId
}
and then
let devAuth = DeveloperAuthenticatedIdentityProvider(regionType: COGNITO_REGION, identityPoolId: COGNITO_POOL_ID, useEnhancedFlow: true, identityProviderManager:nil)
let credentialsProvider =
AWSCognitoCredentialsProvider(regionType: COGNITO_REGION, identityProvider:devAuth)
let configuration =
AWSServiceConfiguration(region: S3_REGION, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
after configuring these things tried to upload using AWSS3TransferManager
let transferManager = AWSS3TransferManager.default()
let uploadingFileURL = URL(fileURLWithPath: "your/file/path/myTestFile.txt")
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.bucket = "myBucket"
uploadRequest.key = "myTestFile.txt"
uploadRequest.body = uploadingFileURL
transferManager.upload(uploadRequest).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in
if let error = task.error as? NSError {
if error.domain == AWSS3TransferManagerErrorDomain, let code = AWSS3TransferManagerErrorType(rawValue: error.code) {
switch code {
case .cancelled, .paused:
break
default:
print("Error uploading: \(uploadRequest.key) Error: \(error)")
}
} else {
print("Error uploading: \(uploadRequest.key) Error: \(error)")
}
return nil
}
let uploadOutput = task.result
print("Upload complete for: \(uploadRequest.key)")
return nil
})
Whenever I call Upload method it shows
[Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=8
"(null)" UserInfo={__type=NotAuthorizedException,
message=Unauthenticated access is not supported for this identity
pool.}]
also DeveloperAuthenticatedIdentityProvider not getting fired
kindly please help.
When you using Developer authenticated identity for cognito identity provider you need not use
AWSS3TransferManager.default()
You need to register the AWSServiceConfiguration to the AWSS3TransferManager with a key.
AWSS3TransferManager.register(with: configuration!, forKey:
"KEY")
Try this way:
let devAuth = DeveloperAuthenticatedIdentityProvider(regionType: COGNITO_REGION, identityPoolId: COGNITO_POOL_ID, useEnhancedFlow: true, identityProviderManager:nil)
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: COGNITO_REGION, identityProvider:devAuth)
let configuration = AWSServiceConfiguration(region: S3_REGION, credentialsProvider:credentialsProvider)
AWSS3TransferManager.register(with: configuration!, forKey: "YOUR_KEY")
//Start Upload
let uploadRequest = AWSS3TransferManagerUploadRequest()
//Set all properties to uploadRequest
AWSS3TransferManager.s3TransferManager(forKey: "YOUR_KEY").upload(uploadRequest!).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in
// Do something with the response
if task.isCancelled {
print("Cancelled Upload")
}
else if (task.error != nil) {
print("Upload error --> \(task.error)")
}else{
print("Upload success!!! Be happy :)")
}
return task
})
Just try, I think it may work.

Returning ENOTCONN Error

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;
}

Issue Integrating Amazon Simple Email Services API in Swift

I want to use the "verifyEmailIdentity" action which is defined in Objective-C as part of the Amazon Simple Email Service API but I'm having trouble doing so in Swift. I want to call the action in Swift code and have the documentation of the action defined in a pod but I'm not really sure how to go about this.
Here is some sample code but my program doesn't recognize the return type.
func createRequest(verifyEmailIdentityRequest: SESVerifyEmailIdentityRequest) -> AmazonServiceRequest {
var request: AmazonServiceRequest = SESRequest()
request.setParameterValue("VerifyEmailIdentity", forKey: "Action")
request.setParameterValue("2010-12-01", forKey: "Version")
request.delegate = verifyEmailIdentityRequest.delegate
request.credentials = verifyEmailIdentityRequest.credentials()
request.endpoint = verifyEmailIdentityRequest.requestEndpoint()
request.requestTag = verifyEmailIdentityRequest.requestTag()
if verifyEmailIdentityRequest != nil {
if verifyEmailIdentityRequest.emailAddress != nil {
request.setParameterValue("\ (verifyEmailIdentityRequest.emailAddress)", forKey: "\("EmailAddress")")
}
}
return request
}
http://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyEmailIdentity.html
You can achieve that by using the following snippet:
func verifyEmailIdentity(verifyEmailIdentityRequest: AWSSESVerifyEmailIdentityRequest) {
// You should ideally set your configuration in app delegate
// Set the region and cognito pool id
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType: AWSRegionType.Unknown,
identityPoolId: "YOUR_POOL_ID")
let configuration = AWSServiceConfiguration(
region: AWSRegionType.Unknown,
credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
let ses = AWSSES.defaultSES()
ses.verifyEmailIdentity(verifyEmailIdentityRequest).continueWithBlock { (task: AWSTask) -> AnyObject? in
if let error = task.error {
// handle error here
} else if let result = task.result {
// handle result here
}
return nil
}
}
Thanks,
Rohan

Resources