How can I set authentication required for access AWS DynamoDB - ios

First I simply follow the given instruction for accessing the DynamoDB,
After that I build the downloaded sample project named DynamoDBObjectMapper-Sample I got given error log -
Error: Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=8 "(null)" UserInfo={__type=NotAuthorizedException, message=Unauthenticated access is not supported for this identity pool.}
This error are print after executing following code-
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
let queryExpression = AWSDynamoDBScanExpression()
queryExpression.exclusiveStartKey = self.lastEvaluatedKey
queryExpression.limit = 20
dynamoDBObjectMapper.scan(DDBTableRow.self, expression: queryExpression).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask!) -> AnyObject! in
if self.lastEvaluatedKey == nil {
self.tableRows?.removeAll(keepingCapacity: true)
}
if let paginatedOutput = task.result {
for item in paginatedOutput.items as! [DDBTableRow] {
self.tableRows?.append(item)
}
self.lastEvaluatedKey = paginatedOutput.lastEvaluatedKey
if paginatedOutput.lastEvaluatedKey == nil {
self.doneLoading = true
}
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.tableView.reloadData()
if let error = task.error as NSError? {
print("Error: \(error)")
}
return nil
})
So please help me for set the authentication key-

Related

AWS Cognito Signin via Get Session not syncing with identity pool

After signing a user up, I'm logging them in via getSession. If I use the interactive sign in, via AWSCognitoIdentityInteractiveAuthenticationDelegate, then it signs me in properly but via getSession I'm not able to do so. Here's my code.
After calling getSession, I'm getting, the user.isSignedIn is true but
AWSSignInManager.shared.isLoggedIn is false, also AWSIdentityManager.default.identityId is null
When I make the call credentialsProvider!.getIdentityId(), it returns the error "Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=8 "(null)" UserInfo={__type=NotAuthorizedException, message=Unauthenticated access is not supported for this identity pool.}"
Whats more interesting is that this works when the app's a fresh install but doesn't after I do a separate login + logout.
I'm making the following calls:
1) self.pool?.signUp(email, password: password, userAttributes: attributes, validationData: nil)
2) newUser?.getSession(email, password: password, validationData: nil)
3) credentialsProvider!.getIdentityId()
4) credentialsProvider?.credentials()
Here's my signup + sign in code: (I've removed the error prompts and logs for brevity)
self.pool?.signUp(email, password: password, userAttributes: attributes, validationData: nil).continueWith {[weak self] (task: AWSTask<AWSCognitoIdentityUserPoolSignUpResponse>) -> AnyObject? in
guard let strongSelf = self else { return nil }
if let error = task.error as NSError? {
return nil
}
guard let signupResponse = task.result else {
print("Error : No Signup Response")
return nil
}
newUser = signupResponse.user
return newUser?.getSession(email, password: password, validationData: nil)
}
.continueWith(block: {[weak self] (task) in
guard let strongSelf = self else { return nil }
if let error = task.error as NSError? {
return
}
guard let signinResponse = task.result else {
print("Error : No Sign-in Response")
return nil
}
let identityPoolId = Bundle.main.infoDictionary!.nestedDict(key: "AWS").nestedDict(key: "CredentialsProvider").nestedDict(key: "CognitoIdentity").nestedDict(key: "Default")["PoolId"] as! String
credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: identityPoolId)
let configuration = AWSServiceConfiguration(
region: .USEast1,
credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
return credentialsProvider!.getIdentityId()
})
.continueWith(block: { (task) -> Any? in
if let error = task.error {
print("GetIdentityId Error:\(error)")
// Handle error
}
// GetCredentialsForIdentity
let cognitoId = task.result
return credentialsProvider?.credentials()
}).continueWith(block: {
(task: AWSTask) -> Void in
if let _ = task.error {
print("Credentials Error:")
// Handle error
}
print("Task:\(task)")
self.onSignIn()
})
})

Apple Health Kit Error Domain=com.apple.healthkit Code=5 “Authorization not determined”

I hava determined authorization before actually trying to access the user's dateofBirth and biologicalSex. But it's work on simulator.but not on iphone and paired watch.
let birthdayType = HKQuantityType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)
let biologicalSexType = HKQuantityType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex)
let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)
let readDataTypes: Set<HKObjectType> = [quantityType!, birthdayType!, biologicalSexType!]
guard HKHealthStore.isHealthDataAvailable() == true else {
label.setText("not available")
return
}
let readDataTypes: Set<HKObjectType> = self.dataTypesToRead()
healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) -> Void in
if success == false {
self.displayNotAllowed()
}
}
var birthDay: Date! = nil
do {
birthDay = try self.healthStore.dateOfBirth()
} catch let error as NSError{
print("Either an error occured fetching the user's age information or none has been stored yet. \(error)")
return -1
}
var biologicalSex:HKBiologicalSexObject! = nil
do {
try biologicalSex = self.healthStore.biologicalSex()
}catch let error as NSError{
print("Failed to read the biologicalSex! \(error)")
}
This is a concurrency problem, not a HealthKit problem.
requestAuthorization may display a dialog and gives you the result in a background process.
You have to wait for the answer of requestAuthorization before you continue reading birthday and biologicalSex.

AWS dynamodb Query crashes most of the time

i'm trying to download user data from AWS DynamoDB like this:
func downloadUserData(id: String) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let qe = AWSDynamoDBQueryExpression()
qe.hashKeyAttribute = "id"
qe.hashKeyValues = id
dynamoDBObjectMapper!.query(DDBUser.self, expression: qe).continueWithBlock { (task: AWSTask) -> AnyObject? in
if task.error != nil {
NSLog("🦁🦁🦁\(self)")
NSLog("🦁Fehler beim Laden der Userdaten: \(task.error)")
} else {
let paginatedOutput = task.result as! AWSDynamoDBPaginatedOutput
print("output \(paginatedOutput.items)")
for user in paginatedOutput.items as! [DDBUser] {
SessionController.sharedInstance.user = user
for (index, tacklId) in SessionController.sharedInstance.user.tacklIds.enumerate() {
if tacklId == "empty" {
SessionController.sharedInstance.user.tacklIds.removeAtIndex(index)
}
}
if !(SessionController.sharedInstance.user.endpoints.contains(SessionController.sharedInstance.currEndpoint!)) {
SessionController.sharedInstance.user.endpoints += [SessionController.sharedInstance.currEndpoint!]
}
}
NSLog("User Download Complete")
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.userdataDelegate?.userdataDownloadComplete!()
}
}
return nil
}
}
Not alway, but most of the time, the Execution stops at this line:
for user in paginatedOutput.items as! [DDBUser] {
With this Error code:
exc_breakpoint (code=1, subcode=0x10015d440)
It even happens with Breakpoints disabled and i can't continue with the Execution.
The line before the break:
print("output \(paginatedOutput.items)")
works well. Could the problem be on another thread and it falsely shows me the error here? How to best debug this? Thank you
You are trying to use
let qe = AWSDynamoDBQueryExpression()
qe.hashKeyAttribute = "id"
qe.hashKeyValues = id
which is deprecated. I would suggest you use 'keyConditionExpression' and 'expressionAttributeValues' instead.
Thanks,
Rohan

Can't upload photo to googleDrive from ios

I followed the tutorial from https://developers.google.com/drive/ios/quickstart
i register my app, got secret key and put it in the appication, getting some token here:
func viewController(vc : UIViewController,
finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) {
if let error = error {
service.authorizer = nil
showAlert("Authentication Error", message: error.localizedDescription)
return
}
service.authorizer = authResult
It's fine. But when i tried to upload photo to google disc - i got this error:
{"error":{"code":403,"message":"Insufficient Permission","data":[{"domain":"global","reason":"insufficientPermissions","message":"Insufficient Permission"}]},"id":"gtl_1"}
2016-04-23 14:21:06.329 PROJECT_NAME[560:210039] Premature failure: upload-status:"final" location:(null)
Here is the code. Can someone tell me what i m doing wrong?
func uploadPhoto(image: UIImage) {
let name = "Photo"
let content = image
let mineType = "image/jpeg"
let metadata = GTLDriveFile()
metadata.name = name
guard let data = UIImagePNGRepresentation(content) else {
return
}
let uploadParameters = GTLUploadParameters(data: data, MIMEType: mineType)
let query = GTLQueryDrive.queryForFilesCreateWithObject(metadata, uploadParameters: uploadParameters) as GTLQueryDrive
service.executeQuery(query) { (ticket, updatedFile, error) in
print(ticket)
if error != nil {
print(error)
}
}
}

how to get session token for google+ login with parse in ios swift2

I am working on one application in which using google plus login
It works fine but I want to integrate with parse also
I have refer for example
func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) {
let token = auth.accessToken
PFUser.becomeInBackground(token, block: { (user : PFUser?, error : NSError?) -> Void in
if error != nil {
print("Error in become user : \(error)")
} else {
print("user : \(user)")
}
})
}
but it give me error like
Error in become user : Optional(Error Domain=Parse Code=209 "invalid session token" UserInfo={code=209, temporary=0, error=invalid session token, NSLocalizedDescription=invalid session token})
I have try also this example Login with google plus in ios on parse.com
but it is in objective c ,try to convert to swift2 but it also give error
Please give me correct solution
Finally solved issues
convert answer into swift code and its work fine
func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) {
if error == nil && auth.expirationDate.compare(NSDate(timeIntervalSinceNow: 0)) == NSComparisonResult.OrderedDescending {
let user = GPPSignIn.sharedInstance().googlePlusUser
let userName = user.name.JSONValueForKey("givenName") as! String
let userEmail = GPPSignIn.sharedInstance().userEmail
let pfUser = PFUser()
pfUser.username = userName
pfUser.email = userEmail
let userPassword = "\(userName)#123"
pfUser.password = userPassword
pfUser.signUpInBackgroundWithBlock({ (success, error : NSError?) -> Void in
if error == nil {
let plusService = GTLServicePlus()
plusService.retryEnabled = true
plusService.authorizer = GPPSignIn.sharedInstance().authentication
let query : GTLQueryPlus! = GTLQueryPlus.queryForPeopleGetWithUserId("me") as! GTLQueryPlus
plusService.executeQuery(query, completionHandler: { (ticket, person, error) -> Void in
if error != nil {
print("Error in execute query : \(error!)")
} else {
let aPerson : GTLPlusPerson! = person as! GTLPlusPerson
let imgUrl = aPerson.image.url
if let imgData = NSData(contentsOfURL: NSURL(string: imgUrl)!) {
self.userProfilePic.image = UIImage(data: imgData)
}
let currentUser = PFUser.currentUser()
currentUser?.username = aPerson.displayName
currentUser?.saveInBackground()
}
})
} else {
print("Error in signup : \(error!.localizedDescription)")
PFUser.logInWithUsernameInBackground(self.userName, password: userPassword, block: { (user : PFUser?, error : NSError?) -> Void in
if error == nil {
print("Login Sccessfully")
} else {
print("Error in login : \(error!.localizedDescription)")
}
})
}
})
} else {
print("Error in authentication : \(error.localizedDescription)")
}
}
Hope Help to someone!!!
I don't think it's a matter of incorrect translation to Swift (as the error is generated by Parse itself during the runtime, not the Swift compiler or the Swift runtime). Try using "PFUser.enableRevocableSessionInBackground()". For more details please visit https://parse.com/tutorials/session-migration-tutorial. Hope it'll help you. Cheers.

Resources