I have an issue with my logic trying to invoke the AWS Recognition Compare Faces api using IOS Swift. There isn't any documentation for Swift yet (as of this posting), but believe I may have the request set up correctly, just not invoking it correctly to receive the response object and confirm the results.
Any advice?
let sourceImage = AWSRekognitionImage()
let sourceImageS3Object = AWSRekognitionS3Object()
sourceImageS3Object?.bucket = "face-badges"
sourceImageS3Object?.name = "me.jpg"
sourceImage?.s3Object = sourceImageS3Object
let targetImage = AWSRekognitionImage()
let targetImageS3Object = AWSRekognitionS3Object()
targetImageS3Object?.bucket = "face-badges"
targetImageS3Object?.name = "me2.jpg"
targetImage?.s3Object = targetImageS3Object
let request = AWSRekognitionCompareFacesRequest()
request?.similarityThreshold = 90
request?.sourceImage = sourceImage
request?.targetImage = targetImage
let key = "testCompareFaces"
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.USEast1,
identityPoolId:"xxxxx")
let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider)
AWSRekognition.register(with: configuration!, forKey: key)
AWSRekognition(forKey: key).compareFaces(AWSRekognitionCompareFacesRequest()).continueWith(block: {(_ task: AWSTask) -> Any in
print("completed")
return true;
}).waitUntilFinished()
The following sample test in the SDK demonstrated how to compare two faces in ObjC.
https://github.com/aws/aws-sdk-ios/blob/master/AWSRekognitionUnitTests/AWSGeneralRekognitionTests.m#L60
Corresponding snippet in Swift would look something like :
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")
Hope that helps!
Related
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)
}
}
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
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)
}
}
}
}
I'm trying to use the Google Drive for iOS API to upload a file from my app. However, the upload doesn't seem to finish, ever, even with an error. In fact, my uploadProgressBlock is not even being called, so I suspect it is not starting.
My class properties:
let kKeychainItemName = "Drive API"
let kClientID = "*******"
let kClientSecret = "*****"
let scopes = [kGTLAuthScopeDrive]
let service = GTLServiceDrive()
Here is the authentication code:
//Google Drive authentication initialization
service.authorizer = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName(
kKeychainItemName,
clientID: kClientID,
clientSecret: kClientSecret
)
And here is the upload code (I'm only doing a test file right now):
let title = "Hello.txt"
let content = "hello world"
let mimeType = "text/plain"
let metaData = GTLDriveFile()
metaData.title = title
let data = content.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let uP = GTLUploadParameters(data: data!, MIMEType: mimeType)
let query = GTLQueryDrive.queryForFilesInsertWithObject(metaData, uploadParameters: uP)
let serviceTicket = service.executeQuery(query, completionHandler: {(ticket, file, error) -> Void in
println("complete")
})
serviceTicket.uploadProgressBlock = {(ticket, written, total) in
println("making progress")
}
As you can see most of my code is similar to Google's quickstart guide. Also, the app authenticates properly.
I am developing an app which needs to store images in Azure using Swift.
Is there any example that will be helpful ? If not can you give me a suggestion ?
Here is a simple example.
1- Start here: https://azure.microsoft.com/en-us/documentation/articles/storage-ios-how-to-use-blob-storage/
2- Get the SDK
3- Here is the code:
let account = AZSCloudStorageAccount(fromConnectionString:AZURE_STORAGE_CONNECTION_STRING) //I stored the property in my header file
let blobClient: AZSCloudBlobClient = account.getBlobClient()
let blobContainer: AZSCloudBlobContainer = blobClient.containerReferenceFromName("<yourContainerName>")
blobContainer.createContainerIfNotExistsWithAccessType(AZSContainerPublicAccessType.Container, requestOptions: nil, operationContext: nil) { (NSError, Bool) -> Void in
if ((NSError) != nil){
NSLog("Error in creating container.")
}
else {
let blob: AZSCloudBlockBlob = blobContainer.blockBlobReferenceFromName(<nameOfYourImage> as String) //If you want a random name, I used let imageName = CFUUIDCreateString(nil, CFUUIDCreate(nil))
let imageData = UIImagePNGRepresentation(<yourImageData>)
blob.uploadFromData(imageData!, completionHandler: {(NSError) -> Void in
NSLog("Ok, uploaded !")
})
}
}
Enjoy :)
You have to use their REST API, but they're working on an SDK right now.
There are a couple of examples of using their REST API on iOS. A cursory search brings up: Uploading to azure blob storage from SAS URL returns 404 status
There is also this example on Github - https://github.com/Ajayi13/BlobExample-Swift
In iOS 11 and Swift 4, you can do like this:
private let containerName = "<Your Name>"
private let connectionString = "<Your String>"
do {
let account = try AZSCloudStorageAccount(fromConnectionString: connectionString)
let blobClient = account?.getBlobClient()
let blobContainer = blobClient?.containerReference(fromName: containerName)
let currentDate = Date()
let fileName = String(currentDate.timeIntervalSinceReferenceDate)+".jpg"
let blob = blobContainer?.blockBlobReference(fromName: now)
blob?.upload(from: imageData, completionHandler: {(error)->Void in
print(now, "uploaded!") // imageData is the data you want to upload
})
} catch {
print(error)
}
This is just an example. Hope it helps.