问题描述
尽管 AWS Cognito 指示设备已登录且已获取 IdentityID,但我仍无法执行 S3 上传。
存储错误描述为“会话过期无法获取身份 ID”。这与返回并传递到 s3 上传文件函数的身份 ID 无关。
func SignIn() {
awsmobileclient.federatedSignIn(providerName: IdentityProvider.apple.rawValue,token: identityToken) { (userState,error) in
if let error = error {
print("Error in federatedSignIn: \(error)")
return
}
guard let userState = userState else {
print("userState unexpectedly nil")
return
}
print("federatedSignIn successful: \(userState.rawValue)")
sleep(5)
// Retrieve your Amazon Cognito ID
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .CACentral1,identityPoolId: "ca-central-1:3e8d12d5-9739-4934-8eb0-df6bec232d77")
let configuration = AWSServiceConfiguration(region: .CACentral1,credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
credentialsProvider.getIdentityId().continueWith(block: { (task) -> AnyObject? in
if (task.error != nil) {
print("Error: " + task.error!.localizedDescription)
}
else {
// the task result will contain the identity id
let cognitoId = task.result!
print("Cognito id: \(cognitoId)")
UserDefaults.standard.set(cognitoId,forKey: "cognitoId")
}
return task;
})
}
- 将数据上传到 S3
func uploadData(key: String,data: Data) {
var progressSink: AnyCancellable?
var resultSink: AnyCancellable?
let options = StorageUploadDataRequest.Options(accessLevel: .private,targetIdentityId: UserDefaults.standard.string(forKey: "cognitoId"),contentType: "image/jpeg")
let storageOperation = Amplify.Storage.uploadData(key: key,data: data,options: options)
progressSink = storageOperation.progresspublisher.sink { progress in print("Progress: \(progress)") }
resultSink = storageOperation.resultPublisher.sink {
if case let .failure(storageError) = $0 {
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
}
receiveValue: { data in
print("Completed: \(data)")
}
}
解决方法
事实证明这很可能是由于 AWS Cognito 设置造成的。 AWS Cognito 配置为“允许访问未经身份验证的用户”未选中,允许基本(经典)流选中,Apple 服务 ID 应为捆绑 ID、角色选择默认值、禁用属性。
这是使用 AWS Amplify Escape Hatch to AWS Mobile Client SDK 和 AWSMobileClient.federatedSignIn 完成的