Swift - AWS Authentication fetchSession - make global function

Viewed 66

I am using AWS authentication on my app. And I want to create a global function for fetching the user token so I can access it anywhere in the app whenever I need to fetch the new id token, the token is changing every 5 mins so I need to call it from time to time. I do it like this

    func fetchSession() {
        Amplify.Auth.fetchAuthSession { result in
            do {
                let session = try result.get()

                // Get cognito user pool token
                if let cognitoTokenProvider = session as? AuthCognitoTokensProvider {
                    let tokens = try cognitoTokenProvider.getCognitoTokens().get()

                    return tokens.idToken
                }
            } catch {
                print("Fetch auth session failed with error - \(error)")
            }
        }
    }

but I am getting this error

Unexpected non-void return value in void function

I also try to make it like this

func fetchSession() {
        let token = Amplify.Auth.fetchAuthSession { result -> AnyObject in
            do {
                let session = try result.get()

                // Get cognito user pool token
                if let cognitoTokenProvider = session as? AuthCognitoTokensProvider {
                    let tokens = try cognitoTokenProvider.getCognitoTokens().get()

                    return tokens.idToken
                }
            } catch {
                print("Fetch auth session failed with error - \(error)")
            }
        }
    }

and this is the error I got

Cannot convert value of type '(AmplifyOperation<AuthFetchSessionRequest, AuthSession, AuthError>.OperationResult) -> AnyObject' (aka '(Result<AuthSession, AuthError>) -> AnyObject') to expected argument type '((AmplifyOperation<AuthFetchSessionRequest, AuthSession, AuthError>.OperationResult) -> Void)?' (aka 'Optional<(Result<AuthSession, AuthError>) -> ()>')
1 Answers

Looks like you need to specify what fetchSession will return. Right now you are saying it will return Void because you have neglected the return type.

Here is an example of specifying the returned type.

func fetchSession() -> String? {
  // ...
  do {
    // ...
    return tokens.idToken // I assume idToken is a String
 } catch {
   print("Fetch auth session failed with error - \(error)")
   return nil
 }
}

Do not forgot to return nil in the catch or rethrow the error.

Swift docs on functions: https://docs.swift.org/swift-book/LanguageGuide/Functions.html

Related