使用 Alamofire 快速关闭

编程入门 行业动态 更新时间:2024-10-11 13:28:16
本文介绍了使用 Alamofire 快速关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在对服务器进行 API 调用.我正在利用 Alamofire 来处理这个问题.我正在尝试创建一个函数,该函数使用 Alamofire 的 GET 函数返回一个基于自定义类的对象,该类包含此 GET 函数提供的各种输出.

I am making API calls to a server. I am leveraging Alamofire to handle this. I'm trying to create a function that uses Alamofire's GET function to return an object based on a custom class that holds the various outputs provided by this GET function.

我不清楚这样做的方式.

It's not clear to me the way in which to do this.

这是我的自定义类,用于保存有关响应的详细信息:

Here's my custom class that will hold details about the response:

import Foundation class ResponsePackage { var success = false var response: AnyObject? = nil var error: NSError? = nil }

在另一个类中,我有以下功能:

In another class I have the following function:

func get(apiEndPoint: NSString) -> ResponsePackage { let responsePackage = ResponsePackage() Alamofire .request(.GET, apiEndPoint) .responseJSON {(request, response, JSON, error) in responsePackage.response = JSON responsePackage.success = true responsePackage.error = error } return responsePackage }

这将返回 nil,因为在 return 执行之前对服务器的调用尚未完成.我知道我应该能够用闭包来做到这一点,但我不知道如何构造它.

This returns nil as the call to the server is not complete before the return gets executed. I know that I should be able to do this with closures, but I am not sure how to construct this.

推荐答案

{} 之间的代码相当于 Objective-C 中的代码块:这是一段异步执行的代码.

The code between the {} is the equivalent of block in objective-C : this is a chunk of code that gets executed asynchronously.

您犯的错误是您放置 return 语句的位置:当您启动请求时,{} 中的代码在框架收到响应之前不会执行,因此当 return 语句到达,很可能,仍然没有响应.您可以简单地移动该行:

The error you made is where you put your return statement : when you launch your request, the code in {} is not executed until the framework received a response, so when the return statement is reached, chances are, there is still no response. You could simply move the line :

return responsePackage

在闭包内,所以 func 只有在收到响应时才返回.这是一种简单的方法,但它并不是真正的最佳方法:您的代码将卡在等待答案中.最好的方法是使用闭包.这看起来像:

inside the closure, so the func return only when it has received a response. This is a simple way, but it's not really optimal : your code will get stuck at waiting for the answers. The best way you can do this is by using closure, too. This would look something like :

func get(apiEndPoint: NSString, completion: (response: ResponsePackage) -> ()) -> Bool { let responsePackage = ResponsePackage() Alamofire .request(.GET, apiEndPoint) .responseJSON {(request, response, JSON, error) in responsePackage.response = JSON responsePackage.success = true responsePackage.error = error completion(response: responsePackage) } }

更多推荐

使用 Alamofire 快速关闭

本文发布于:2023-11-26 02:15:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!