我有一个单例 URLSession,它将响应数据解析到字典中。我想在后续代码段中使用该字典中的单个值,但无法弄清楚如何将该值从当前所在的范围传递出去。
这是现在的代码:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
debugPrint ("error: (error!)")
return
}
guard let content = data else {
debugPrint("No data")
return
}
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
debugPrint("Not containing JSON")
return
}
if let idToken = json["id_token"] as? String {
let privateToken = idToken;
debugPrint("Gotten json response dictionary is (idToken)")
}
}
task.resume()
return privateToken
当前return privateToken
上出现IDE错误,指出我正在使用未解析的标识符:privateToken
。
如何获取字符串 idToken 并将其作为私有令牌返回以供其他地方使用?
你能使用这样的完成处理程序吗:
func getPrivateToken(completion: @escaping(String) -> (), failure: @escaping (Error) -> ()) {
URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
debugPrint ("error: (error!)")
failure(error)
return
}
guard let content = data else {
debugPrint("No data")
failure(NSError(domain: "Your error message here.", code: 401, userInfo: nil))
return
}
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
debugPrint("Not containing JSON")
failure(NSError(domain: "Your error message here.", code: 401, userInfo: nil))
return
}
if let idToken = json["id_token"] as? String {
completion(idToken)
debugPrint("Gotten json response dictionary is (idToken)")
}
}.resume()
}
并像这样使用它:
func exampleFunction() {
self.getPrivateToken(completion: { (token) in
// Do what ever you need with the token here.
print("ID token is: (token)")
}) { (error) in
// Present error here
}
}