Created
October 21, 2015 22:26
-
-
Save zsim0n/abc38d08904dbd4afd42 to your computer and use it in GitHub Desktop.
AWSCognito iOS Swift Share Identity between app and extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Framework | |
import Foundation | |
import AWSCognito //pod | |
import KeychainAccess //pod | |
public struct Apple { | |
public struct KeyChain { | |
public static let Group = "YOUR GROUP NAME" | |
public static let Service = "YOUR SERVICE NAME" | |
} | |
} | |
public struct Amazon { | |
public struct Cognito { | |
public static let PoolId = "YOUR POOL ID" | |
public static let Region = AWSRegionType | |
} | |
} | |
public class MyCognito { | |
public var identityId:String? = "" | |
var credentialsProvider: AWSCognitoCredentialsProvider | |
let cognito: AWSCognito | |
let keychain = Keychain(service: Apple.KeyChain.Service, accessGroup: Apple.KeyChain.Group) | |
init() { | |
credentialsProvider = AWSCognitoCredentialsProvider( | |
regionType: Amazon.Cognito.Region, | |
identityPoolId: Amazon.Cognito.PoolId) | |
if let kid = try? keychain.getString("CognitoIdentityId") { | |
credentialsProvider = AWSCognitoCredentialsProvider( | |
regionType: Amazon.Cognito.Region, | |
identityId: kid, | |
identityPoolId: Amazon.Cognito.PoolId, | |
logins: nil) | |
identityId = kid | |
} | |
let configuration = AWSServiceConfiguration( | |
region: Amazon.Cognito.Region, | |
credentialsProvider: credentialsProvider) | |
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration | |
cognito = AWSCognito.defaultCognito() | |
} | |
func requestIdentity() { | |
credentialsProvider.getIdentityId().continueWithBlock() { (task) -> AnyObject! in | |
if let error = task.error { | |
print("Could not request identity: \(error.userInfo)") | |
} else { | |
self.identityId = self.credentialsProvider.identityId | |
if let error = try? keychain.set(self.credentialsProvider.identityId, key: "CognitoIdentityId") { | |
print("error: \(error)") | |
} | |
} | |
return nil | |
} | |
} | |
} | |
class ViewController { | |
let mycognito = MyCognito() | |
override func viewDidLoad() { | |
mycognito.requestIdentity() | |
} | |
} | |
class TodayViewController { | |
let mycognito = MyCognito() | |
override func viewDidLoad() { | |
mycognito.requestIdentity() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment