Swift - AWS Authentication fetchSession - make global functi



我在我的应用程序上使用AWS认证。我想创建一个全局函数来获取用户令牌,这样我就可以在应用程序的任何地方访问它,每当我需要获取新的id令牌时,令牌每5分钟改变一次,所以我需要不时地调用它。我是这样做的

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)")
}
}
}

但是我得到这个错误

Unexpected non-void return value in void function

我也试着把它变成这样

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)")
}
}
}

这是我得到的错误

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>) -> ()>')

看起来您需要指定fetchSession将返回什么。现在您说它将返回Void,因为您忽略了返回类型。

下面是指定返回类型的示例:

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

不要忘记在捕获或重新抛出错误时返回nil。

Swift函数文档:https://docs.swift.org/swift-book/LanguageGuide/Functions.html

最新更新