无法跨多个iOS设备同步Amazon Cognito数据集

时间:2016-12-03 20:16:15

标签: ios amazon-web-services swift3 amazon-cognito

我已经能够在单个iOS设备上注册,确认和同步用户数据集,但在尝试在其他设备上同步时遇到了问题。我正在努力弄清楚为什么会这样。在注册过程中,我同步数据集,我可以在联合身份标识浏览器中看到它。但是当在其他设备上同步时,我无法从我的数据集中读取。用户信息是否存储在设备本地?我的Cognito同步逻辑是否不正确?还有另一种方法我应该接近这个吗?以下是我在登录时同步用户数据的代码。在此先感谢..我真的很困惑如何解决这个问题。

func login(usernameText : String, passwordText : String){
    user = self.pool!.getUser(usernameText)
    var userString = ""
    print("Login Current thread \(Thread.current)")

    user?.getSession(usernameText, password: passwordText, validationData: nil).continue({ task in
        DispatchQueue.main.async {
        print(" Session Current thread \(Thread.current)")
        if let err = task.error {  // some sort of error

            print("LOGIN FAILED")
            print(err)
            self.userConfirmed = false
            //print(err.userInfo["message"] as! String)
        }
        else { //Successful login!

            // this gets our token from the User Pool
            let ret = task.result! as AWSCognitoIdentityUserSession
            let myToken = ret.idToken?.tokenString;

            let customcedentialProvider = AWSCustomIdentityProvider(tokens: [AWSCustomIdentityProvider.CognitoTokenKey : myToken!])
            let credentialsProvider = AWSCognitoCredentialsProvider(regionType: CognitoConstants.COGNITO_REGIONTYPE, identityPoolId: CognitoConstants.COGNITO_IDENTITY_POOL_ID,  identityProviderManager: customcedentialProvider)
            let configuration = AWSServiceConfiguration(region: CognitoConstants.COGNITO_REGIONTYPE, credentialsProvider:credentialsProvider)
            AWSServiceManager.default().defaultServiceConfiguration = configuration

            // wipe cached creds
            credentialsProvider.clearKeychain()
            credentialsProvider.clearCredentials()

            // hit it
            credentialsProvider.getIdentityId().continue({ (task: AWSTask!) -> AnyObject! in
                DispatchQueue.main.async {
                print("Current thread \(Thread.current)")
                if (task.error != nil) {
                    print("Error: ")

                } else {
                    print(credentialsProvider.identityId!)
                    // the task result will contain the identity id
                    let credentialsProviderUser = AWSCognitoCredentialsProvider(regionType:.usEast1,identityPoolId:credentialsProvider.identityId!)

                    let configurationUser = AWSServiceConfiguration(region:.usEast1, credentialsProvider:credentialsProviderUser)
                    AWSServiceManager.default().defaultServiceConfiguration = configurationUser

                    // Initialize the Cognito Sync client
                    let syncClient = AWSCognito.default()
                    // Get User Dataset
                    let dataset = syncClient?.openOrCreateDataset("myDataset")
                    print(dataset?.size() as Any)
                    let userData = dataset?.getAll()

                    for (key,value) in userData!{ if "\(value)".characters.count > 0 {userString.append("| Key: \(key) Value: \(value) ");print("| Key: \(key) Value: \(value) ")}
                    }

                }
                let defaults = UserDefaults.standard

                defaults.setValue(userString, forKey: defaultsKeys.keyOne)
                defaults.setValue(passwordText, forKey: defaultsKeys.keyTwo)

                defaults.synchronize()

                }
                return nil
                })
            }}
        return nil
        })
}

// Class for custom tokens
class AWSCustomIdentityProvider: NSObject, AWSIdentityProviderManager
{
    static let FacebookTokenKey = "graph.facebook.com"
    static let GoogleTokenKey = "accounts.google.com"
    static let TwitterTokenKey = "api.twitter.com"
    static let CognitoTokenKey = "cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX"

    var tokens: NSDictionary = [String : String]() as NSDictionary

    init(tokens: [String : String]) {
        self.tokens = tokens as NSDictionary
    }

    func logins() -> AWSTask<NSDictionary> { // AWSIdentityProviderManager delegate method
        return AWSTask(result: tokens)
    }
}

1 个答案:

答案 0 :(得分:0)

我怀疑你没有真正进行身份验证(登录计数为0),并且您看到的同步发生与未经身份验证的身份相关联。

我怀疑这是因为您错过了对凭据的调用。获取身份ID是不够的,如果你从不调用凭证那么......凭证提供者永远不会调用你的logins(),如果他从不调用logins()那么他从来没有看到登录已经完成,因此他永远不会递增登录计数(这就是为什么您可能会在身份上的identityBrowser中看到0次登录)。这意味着您使用的是未经身份验证的身份。

如果您有0个登录计数,则表示您未经过身份验证。

这个答案也可能对你有帮助。

multiple devices cognito ios login

目前还不清楚您的问题是如何为Google和Twitter等生成令牌,但我应该指出用户池能够返回登录信息。