使用Alamofire快速关闭 [英] Swift closure with Alamofire

查看:75
本文介绍了使用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.

这是我的自定义类,其中包含有关响应的详细信息:

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 因为在执行返回之前,对服务器的调用尚未完成。我知道我应该可以使用闭包来做到这一点,但是我不确定如何构造它。

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快速关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆