【问题标题】:Class variable assignment is not working inside a Alamofire request block类变量分配在 Alamofire 请求块中不起作用
【发布时间】:2019-05-16 17:08:41
【问题描述】:

我正在尝试将 Alamofire 请求结果分配给 TableView 类变量。

我意识到当我在Alamofire 请求块中使用 self.notifications 变量时,它可以工作。但是当我在Alamofire 之外调用 self.notifications 时,它是 nil 并且 self.notifications 不是通过引用分配的。好像是复制变量

class NotificationsTableView: UITableViewController{

    var notifications: Notification!
    let uri = Helper.URLDEV + "/api_x/notifications/"
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.cellLayoutMarginsFollowReadableWidth = true
        self.tableView.delegate = self
        self.tableView.dataSource = self
        print("Table loaded")
        let auth_code = ["Authorization": "Token " + Helper.getMyToken() ]
        Alamofire.request(self.uri, parameters: nil, encoding: URLEncoding.default, headers: auth_code).responseJSON { response in
            guard let data = response.data else { return }
            do {
                let decoder = JSONDecoder()
                //This is working properly
                self.notifications = try decoder.decode(Notification.self, from: data)
                print(self.notifications?.results?[2].notificationData?.body ?? 999)

            } catch let error {
                print(error)
            }
        }
        print("URI: \(uri)")
        //Here is just nil, if I didn't assign a value before
        print(self.notifications == nil)

我希望 self.notifications 在Alamofire 请求之后不会为零

【问题讨论】:

  • 这是任何异步调用背后的逻辑,你需要从 Alamofire 回调开始旅程

标签: ios swift alamofire


【解决方案1】:

alamofire 响应中的代码将在从 URL 接收到一些响应时执行。在这里,执行指针不会等待该响应,因为它是异步回调,并将继续执行下一条语句。所以它将首先在 Alamofire 之外执行语句,并且由于它没有使用任何值初始化,它将为 nil,并且在收到一些响应后,将一些值分配给类变量。

下面的链接将能够让您了解异步代码

https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f

【讨论】:

  • 谢谢@BhargavR,这是开始理解异步代码的好点
【解决方案2】:

最后,使用 repo 中的 Alamofire 同步解决了问题,甚至使用更简洁的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2013-09-26
    • 1970-01-01
    • 2019-08-17
    相关资源
    最近更新 更多