[英]Swift - Completion handler code not running
Im having trouble getting the code in my completion handler to run when I call it in my view.当我在我的视图中调用它时,我无法让我的完成处理程序中的代码运行。 I have been trying to figure out why it is not working but had no luck.
我一直试图弄清楚为什么它不起作用但没有运气。 I believe it has to do with the DispatchQueue but im not sure.
我相信这与 DispatchQueue 有关,但我不确定。 This is my view code im triyng to run.
这是我试图运行的视图代码。 If anyone can explain why the code is not running, that would be much appreciated
如果有人能解释为什么代码没有运行,那将不胜感激
struct SignIn: View {
@Binding var userID: String
@Binding var passcode: String
@EnvironmentObject var authentication: AuthenticationCheck
var body: some View {
Button(action: {
// Note: Works once data is decoded
// Completion handler not running
print("Button action")
NetworkService.shared.signIn(username: userID, password: passcode) { (result) in
switch result {
case .success(let user):
// Does not run
print("This user last name is: \(userresult.login.userName)")
authentication.updateValidation(success: true)
case .failure(let error):
print("The error is: \(error.localizedDescription)")
}
}
}) {
Text("Sign In")
.multilineTextAlignment(.center)
.padding()
}
.frame(width: 150.0, height: 43.0)
.foregroundColor(.white)
.cornerRadius(20)
.disabled(userID.isEmpty || passcode.isEmpty)
}
}
This is some of the code for my network call这是我的网络调用的一些代码
func request<T: Codable>(endPoint: EndPoint, method: Method, parameters: [String: Any]? = nil, completion: @escaping(Result<T, Error>) -> Void) {
// Creates a urlRequest
guard let request = createRequest(endPoint: endPoint, method: method, parameters: parameters) else {
completion(.failure(AppError.invalidUrl))
return
}
let session = URLSession.shared
session.dataTask(with: request) { data, response, error in
var results: Result<Data, Error>?
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
completion(.failure(AppError.badStatusCode))
return
}
if let response = response {
// Gets the JSESSIONID
let cookieName = "JSESSIONID"
if let cookie = HTTPCookieStorage.shared.cookies?.first(where: { $0.name == cookieName }) {
debugPrint("\(cookieName): \(cookie.value)")
}
print(response)
}
// Look into this
if let data = data {
results = .success(data)
} else if let error = error {
results = .failure(error)
print("Server Error: \(error.localizedDescription)")
}
DispatchQueue.main.async {
self.handleResponse(result: results, completion: completion)
}
}.resume()
}
private func handleResponse<T: Decodable>(result: Result<Data, Error>?, completion: (Result<T, Error>) -> Void) {
guard let result = result else {
completion(.failure(AppError.unknownError))
return
}
switch result {
case .success(let data):
let decoder = JSONDecoder()
// Decodes that json data
do {
let json = try decoder.decode(T.self, from: data)
completion(.success(json))
} catch {
print(error.localizedDescription)
}
case .failure(let error):
completion(.failure(error))
}
}
Im using this function to make the request我使用这个函数来提出请求
func signIn(username: String, password: Any, completion: @escaping (Result<LoginResponseData.Root.Result.Login.UserName.Name, Error>) -> Void) {
let params = ["username": "\(username)", "password": "\(password)"]
request(endPoint: .Login, method: .post, parameters: params, completion: completion)
}
Usually when your escaping closure isn't being called, it usually means you have forgotten to call it in functions relating.通常,当您的转义闭包未被调用时,通常意味着您忘记在相关函数中调用它。 Looking at your code, I think you need a completion in your
case .success
:查看您的代码,我认为您的情况需要完成
case .success
:
case .success(let data):
let decoder = JSONDecoder()
// Decodes that json data
do {
let json = try decoder.decode(LoginResponseData.Root.self, from: data)
// This prints
print(json.result.login.userName.name.firstName)
} catch {
print(error.localizedDescription)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.